spirv_emit_context.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  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 <bit>
  7. #include <climits>
  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. DefineConstantBufferIndirectFunctions(program.info);
  428. DefineStorageBuffers(program.info, storage_binding);
  429. DefineTextureBuffers(program.info, texture_binding);
  430. DefineImageBuffers(program.info, image_binding);
  431. DefineTextures(program.info, texture_binding, bindings.texture_scaling_index);
  432. DefineImages(program.info, image_binding, bindings.image_scaling_index);
  433. DefineAttributeMemAccess(program.info);
  434. DefineGlobalMemoryFunctions(program.info);
  435. DefineRescalingInput(program.info);
  436. }
  437. EmitContext::~EmitContext() = default;
  438. Id EmitContext::Def(const IR::Value& value) {
  439. if (!value.IsImmediate()) {
  440. return value.InstRecursive()->Definition<Id>();
  441. }
  442. switch (value.Type()) {
  443. case IR::Type::Void:
  444. // Void instructions are used for optional arguments (e.g. texture offsets)
  445. // They are not meant to be used in the SPIR-V module
  446. return Id{};
  447. case IR::Type::U1:
  448. return value.U1() ? true_value : false_value;
  449. case IR::Type::U32:
  450. return Const(value.U32());
  451. case IR::Type::U64:
  452. return Constant(U64, value.U64());
  453. case IR::Type::F32:
  454. return Const(value.F32());
  455. case IR::Type::F64:
  456. return Constant(F64[1], value.F64());
  457. default:
  458. throw NotImplementedException("Immediate type {}", value.Type());
  459. }
  460. }
  461. Id EmitContext::BitOffset8(const IR::Value& offset) {
  462. if (offset.IsImmediate()) {
  463. return Const((offset.U32() % 4) * 8);
  464. }
  465. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(24u));
  466. }
  467. Id EmitContext::BitOffset16(const IR::Value& offset) {
  468. if (offset.IsImmediate()) {
  469. return Const(((offset.U32() / 2) % 2) * 16);
  470. }
  471. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(16u));
  472. }
  473. void EmitContext::DefineCommonTypes(const Info& info) {
  474. void_id = TypeVoid();
  475. U1 = Name(TypeBool(), "u1");
  476. F32.Define(*this, TypeFloat(32), "f32");
  477. U32.Define(*this, TypeInt(32, false), "u32");
  478. S32.Define(*this, TypeInt(32, true), "s32");
  479. private_u32 = Name(TypePointer(spv::StorageClass::Private, U32[1]), "private_u32");
  480. input_f32 = Name(TypePointer(spv::StorageClass::Input, F32[1]), "input_f32");
  481. input_u32 = Name(TypePointer(spv::StorageClass::Input, U32[1]), "input_u32");
  482. input_s32 = Name(TypePointer(spv::StorageClass::Input, TypeInt(32, true)), "input_s32");
  483. output_f32 = Name(TypePointer(spv::StorageClass::Output, F32[1]), "output_f32");
  484. output_u32 = Name(TypePointer(spv::StorageClass::Output, U32[1]), "output_u32");
  485. if (info.uses_int8 && profile.support_int8) {
  486. AddCapability(spv::Capability::Int8);
  487. U8 = Name(TypeInt(8, false), "u8");
  488. S8 = Name(TypeInt(8, true), "s8");
  489. }
  490. if (info.uses_int16 && profile.support_int16) {
  491. AddCapability(spv::Capability::Int16);
  492. U16 = Name(TypeInt(16, false), "u16");
  493. S16 = Name(TypeInt(16, true), "s16");
  494. }
  495. if (info.uses_int64) {
  496. AddCapability(spv::Capability::Int64);
  497. U64 = Name(TypeInt(64, false), "u64");
  498. }
  499. if (info.uses_fp16) {
  500. AddCapability(spv::Capability::Float16);
  501. F16.Define(*this, TypeFloat(16), "f16");
  502. }
  503. if (info.uses_fp64) {
  504. AddCapability(spv::Capability::Float64);
  505. F64.Define(*this, TypeFloat(64), "f64");
  506. }
  507. }
  508. void EmitContext::DefineCommonConstants() {
  509. true_value = ConstantTrue(U1);
  510. false_value = ConstantFalse(U1);
  511. u32_zero_value = Const(0U);
  512. f32_zero_value = Const(0.0f);
  513. }
  514. void EmitContext::DefineInterfaces(const IR::Program& program) {
  515. DefineInputs(program);
  516. DefineOutputs(program);
  517. }
  518. void EmitContext::DefineLocalMemory(const IR::Program& program) {
  519. if (program.local_memory_size == 0) {
  520. return;
  521. }
  522. const u32 num_elements{Common::DivCeil(program.local_memory_size, 4U)};
  523. const Id type{TypeArray(U32[1], Const(num_elements))};
  524. const Id pointer{TypePointer(spv::StorageClass::Private, type)};
  525. local_memory = AddGlobalVariable(pointer, spv::StorageClass::Private);
  526. if (profile.supported_spirv >= 0x00010400) {
  527. interfaces.push_back(local_memory);
  528. }
  529. }
  530. void EmitContext::DefineSharedMemory(const IR::Program& program) {
  531. if (program.shared_memory_size == 0) {
  532. return;
  533. }
  534. const auto make{[&](Id element_type, u32 element_size) {
  535. const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)};
  536. const Id array_type{TypeArray(element_type, Const(num_elements))};
  537. Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  538. const Id struct_type{TypeStruct(array_type)};
  539. MemberDecorate(struct_type, 0U, spv::Decoration::Offset, 0U);
  540. Decorate(struct_type, spv::Decoration::Block);
  541. const Id pointer{TypePointer(spv::StorageClass::Workgroup, struct_type)};
  542. const Id element_pointer{TypePointer(spv::StorageClass::Workgroup, element_type)};
  543. const Id variable{AddGlobalVariable(pointer, spv::StorageClass::Workgroup)};
  544. Decorate(variable, spv::Decoration::Aliased);
  545. interfaces.push_back(variable);
  546. return std::make_tuple(variable, element_pointer, pointer);
  547. }};
  548. if (profile.support_explicit_workgroup_layout) {
  549. AddExtension("SPV_KHR_workgroup_memory_explicit_layout");
  550. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR);
  551. if (program.info.uses_int8) {
  552. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR);
  553. std::tie(shared_memory_u8, shared_u8, std::ignore) = make(U8, 1);
  554. }
  555. if (program.info.uses_int16) {
  556. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR);
  557. std::tie(shared_memory_u16, shared_u16, std::ignore) = make(U16, 2);
  558. }
  559. if (program.info.uses_int64) {
  560. std::tie(shared_memory_u64, shared_u64, std::ignore) = make(U64, 8);
  561. }
  562. std::tie(shared_memory_u32, shared_u32, shared_memory_u32_type) = make(U32[1], 4);
  563. std::tie(shared_memory_u32x2, shared_u32x2, std::ignore) = make(U32[2], 8);
  564. std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16);
  565. return;
  566. }
  567. const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)};
  568. const Id type{TypeArray(U32[1], Const(num_elements))};
  569. shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type);
  570. shared_u32 = TypePointer(spv::StorageClass::Workgroup, U32[1]);
  571. shared_memory_u32 = AddGlobalVariable(shared_memory_u32_type, spv::StorageClass::Workgroup);
  572. interfaces.push_back(shared_memory_u32);
  573. const Id func_type{TypeFunction(void_id, U32[1], U32[1])};
  574. const auto make_function{[&](u32 mask, u32 size) {
  575. const Id loop_header{OpLabel()};
  576. const Id continue_block{OpLabel()};
  577. const Id merge_block{OpLabel()};
  578. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type)};
  579. const Id offset{OpFunctionParameter(U32[1])};
  580. const Id insert_value{OpFunctionParameter(U32[1])};
  581. AddLabel();
  582. OpBranch(loop_header);
  583. AddLabel(loop_header);
  584. const Id word_offset{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  585. const Id shift_offset{OpShiftLeftLogical(U32[1], offset, Const(3U))};
  586. const Id bit_offset{OpBitwiseAnd(U32[1], shift_offset, Const(mask))};
  587. const Id count{Const(size)};
  588. OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  589. OpBranch(continue_block);
  590. AddLabel(continue_block);
  591. const Id word_pointer{OpAccessChain(shared_u32, shared_memory_u32, word_offset)};
  592. const Id old_value{OpLoad(U32[1], word_pointer)};
  593. const Id new_value{OpBitFieldInsert(U32[1], old_value, insert_value, bit_offset, count)};
  594. const Id atomic_res{OpAtomicCompareExchange(U32[1], word_pointer, Const(1U), u32_zero_value,
  595. u32_zero_value, new_value, old_value)};
  596. const Id success{OpIEqual(U1, atomic_res, old_value)};
  597. OpBranchConditional(success, merge_block, loop_header);
  598. AddLabel(merge_block);
  599. OpReturn();
  600. OpFunctionEnd();
  601. return func;
  602. }};
  603. if (program.info.uses_int8) {
  604. shared_store_u8_func = make_function(24, 8);
  605. }
  606. if (program.info.uses_int16) {
  607. shared_store_u16_func = make_function(16, 16);
  608. }
  609. }
  610. void EmitContext::DefineSharedMemoryFunctions(const IR::Program& program) {
  611. if (program.info.uses_shared_increment) {
  612. increment_cas_shared = CasLoop(*this, Operation::Increment, shared_memory_u32_type,
  613. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  614. }
  615. if (program.info.uses_shared_decrement) {
  616. decrement_cas_shared = CasLoop(*this, Operation::Decrement, shared_memory_u32_type,
  617. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  618. }
  619. }
  620. void EmitContext::DefineAttributeMemAccess(const Info& info) {
  621. const auto make_load{[&] {
  622. const bool is_array{stage == Stage::Geometry};
  623. const Id end_block{OpLabel()};
  624. const Id default_label{OpLabel()};
  625. const Id func_type_load{is_array ? TypeFunction(F32[1], U32[1], U32[1])
  626. : TypeFunction(F32[1], U32[1])};
  627. const Id func{OpFunction(F32[1], spv::FunctionControlMask::MaskNone, func_type_load)};
  628. const Id offset{OpFunctionParameter(U32[1])};
  629. const Id vertex{is_array ? OpFunctionParameter(U32[1]) : Id{}};
  630. AddLabel();
  631. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  632. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  633. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  634. std::vector<Sirit::Literal> literals;
  635. std::vector<Id> labels;
  636. if (info.loads.AnyComponent(IR::Attribute::PositionX)) {
  637. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  638. labels.push_back(OpLabel());
  639. }
  640. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  641. for (u32 index = 0; index < static_cast<u32>(IR::NUM_GENERICS); ++index) {
  642. if (!info.loads.Generic(index)) {
  643. continue;
  644. }
  645. literals.push_back(base_attribute_value + index);
  646. labels.push_back(OpLabel());
  647. }
  648. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  649. OpSwitch(compare_index, default_label, literals, labels);
  650. AddLabel(default_label);
  651. OpReturnValue(Const(0.0f));
  652. size_t label_index{0};
  653. if (info.loads.AnyComponent(IR::Attribute::PositionX)) {
  654. AddLabel(labels[label_index]);
  655. const Id pointer{is_array
  656. ? OpAccessChain(input_f32, input_position, vertex, masked_index)
  657. : OpAccessChain(input_f32, input_position, masked_index)};
  658. const Id result{OpLoad(F32[1], pointer)};
  659. OpReturnValue(result);
  660. ++label_index;
  661. }
  662. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  663. if (!info.loads.Generic(index)) {
  664. continue;
  665. }
  666. AddLabel(labels[label_index]);
  667. const auto type{AttrTypes(*this, static_cast<u32>(index))};
  668. if (!type) {
  669. OpReturnValue(Const(0.0f));
  670. ++label_index;
  671. continue;
  672. }
  673. const Id generic_id{input_generics.at(index)};
  674. const Id pointer{is_array
  675. ? OpAccessChain(type->pointer, generic_id, vertex, masked_index)
  676. : OpAccessChain(type->pointer, generic_id, masked_index)};
  677. const Id value{OpLoad(type->id, pointer)};
  678. const Id result{type->needs_cast ? OpBitcast(F32[1], value) : value};
  679. OpReturnValue(result);
  680. ++label_index;
  681. }
  682. AddLabel(end_block);
  683. OpUnreachable();
  684. OpFunctionEnd();
  685. return func;
  686. }};
  687. const auto make_store{[&] {
  688. const Id end_block{OpLabel()};
  689. const Id default_label{OpLabel()};
  690. const Id func_type_store{TypeFunction(void_id, U32[1], F32[1])};
  691. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type_store)};
  692. const Id offset{OpFunctionParameter(U32[1])};
  693. const Id store_value{OpFunctionParameter(F32[1])};
  694. AddLabel();
  695. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  696. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  697. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  698. std::vector<Sirit::Literal> literals;
  699. std::vector<Id> labels;
  700. if (info.stores.AnyComponent(IR::Attribute::PositionX)) {
  701. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  702. labels.push_back(OpLabel());
  703. }
  704. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  705. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  706. if (!info.stores.Generic(index)) {
  707. continue;
  708. }
  709. literals.push_back(base_attribute_value + static_cast<u32>(index));
  710. labels.push_back(OpLabel());
  711. }
  712. if (info.stores.ClipDistances()) {
  713. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance0) >> 2);
  714. labels.push_back(OpLabel());
  715. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance4) >> 2);
  716. labels.push_back(OpLabel());
  717. }
  718. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  719. OpSwitch(compare_index, default_label, literals, labels);
  720. AddLabel(default_label);
  721. OpReturn();
  722. size_t label_index{0};
  723. if (info.stores.AnyComponent(IR::Attribute::PositionX)) {
  724. AddLabel(labels[label_index]);
  725. const Id pointer{OpAccessChain(output_f32, output_position, masked_index)};
  726. OpStore(pointer, store_value);
  727. OpReturn();
  728. ++label_index;
  729. }
  730. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  731. if (!info.stores.Generic(index)) {
  732. continue;
  733. }
  734. if (output_generics[index][0].num_components != 4) {
  735. throw NotImplementedException("Physical stores and transform feedbacks");
  736. }
  737. AddLabel(labels[label_index]);
  738. const Id generic_id{output_generics[index][0].id};
  739. const Id pointer{OpAccessChain(output_f32, generic_id, masked_index)};
  740. OpStore(pointer, store_value);
  741. OpReturn();
  742. ++label_index;
  743. }
  744. if (info.stores.ClipDistances()) {
  745. AddLabel(labels[label_index]);
  746. const Id pointer{OpAccessChain(output_f32, clip_distances, masked_index)};
  747. OpStore(pointer, store_value);
  748. OpReturn();
  749. ++label_index;
  750. AddLabel(labels[label_index]);
  751. const Id fixed_index{OpIAdd(U32[1], masked_index, Const(4U))};
  752. const Id pointer2{OpAccessChain(output_f32, clip_distances, fixed_index)};
  753. OpStore(pointer2, store_value);
  754. OpReturn();
  755. ++label_index;
  756. }
  757. AddLabel(end_block);
  758. OpUnreachable();
  759. OpFunctionEnd();
  760. return func;
  761. }};
  762. if (info.loads_indexed_attributes) {
  763. indexed_load_func = make_load();
  764. }
  765. if (info.stores_indexed_attributes) {
  766. indexed_store_func = make_store();
  767. }
  768. }
  769. void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
  770. if (!info.uses_global_memory || !profile.support_int64) {
  771. return;
  772. }
  773. using DefPtr = Id StorageDefinitions::*;
  774. const Id zero{u32_zero_value};
  775. const auto define_body{[&](DefPtr ssbo_member, Id addr, Id element_pointer, u32 shift,
  776. auto&& callback) {
  777. AddLabel();
  778. const size_t num_buffers{info.storage_buffers_descriptors.size()};
  779. for (size_t index = 0; index < num_buffers; ++index) {
  780. if (!info.nvn_buffer_used[index]) {
  781. continue;
  782. }
  783. const auto& ssbo{info.storage_buffers_descriptors[index]};
  784. const Id ssbo_addr_cbuf_offset{Const(ssbo.cbuf_offset / 8)};
  785. const Id ssbo_size_cbuf_offset{Const(ssbo.cbuf_offset / 4 + 2)};
  786. const Id ssbo_addr_pointer{OpAccessChain(
  787. uniform_types.U32x2, cbufs[ssbo.cbuf_index].U32x2, zero, ssbo_addr_cbuf_offset)};
  788. const Id ssbo_size_pointer{OpAccessChain(uniform_types.U32, cbufs[ssbo.cbuf_index].U32,
  789. zero, ssbo_size_cbuf_offset)};
  790. const Id ssbo_addr{OpBitcast(U64, OpLoad(U32[2], ssbo_addr_pointer))};
  791. const Id ssbo_size{OpUConvert(U64, OpLoad(U32[1], ssbo_size_pointer))};
  792. const Id ssbo_end{OpIAdd(U64, ssbo_addr, ssbo_size)};
  793. const Id cond{OpLogicalAnd(U1, OpUGreaterThanEqual(U1, addr, ssbo_addr),
  794. OpULessThan(U1, addr, ssbo_end))};
  795. const Id then_label{OpLabel()};
  796. const Id else_label{OpLabel()};
  797. OpSelectionMerge(else_label, spv::SelectionControlMask::MaskNone);
  798. OpBranchConditional(cond, then_label, else_label);
  799. AddLabel(then_label);
  800. const Id ssbo_id{ssbos[index].*ssbo_member};
  801. const Id ssbo_offset{OpUConvert(U32[1], OpISub(U64, addr, ssbo_addr))};
  802. const Id ssbo_index{OpShiftRightLogical(U32[1], ssbo_offset, Const(shift))};
  803. const Id ssbo_pointer{OpAccessChain(element_pointer, ssbo_id, zero, ssbo_index)};
  804. callback(ssbo_pointer);
  805. AddLabel(else_label);
  806. }
  807. }};
  808. const auto define_load{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  809. const Id function_type{TypeFunction(type, U64)};
  810. const Id func_id{OpFunction(type, spv::FunctionControlMask::MaskNone, function_type)};
  811. const Id addr{OpFunctionParameter(U64)};
  812. define_body(ssbo_member, addr, element_pointer, shift,
  813. [&](Id ssbo_pointer) { OpReturnValue(OpLoad(type, ssbo_pointer)); });
  814. OpReturnValue(ConstantNull(type));
  815. OpFunctionEnd();
  816. return func_id;
  817. }};
  818. const auto define_write{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  819. const Id function_type{TypeFunction(void_id, U64, type)};
  820. const Id func_id{OpFunction(void_id, spv::FunctionControlMask::MaskNone, function_type)};
  821. const Id addr{OpFunctionParameter(U64)};
  822. const Id data{OpFunctionParameter(type)};
  823. define_body(ssbo_member, addr, element_pointer, shift, [&](Id ssbo_pointer) {
  824. OpStore(ssbo_pointer, data);
  825. OpReturn();
  826. });
  827. OpReturn();
  828. OpFunctionEnd();
  829. return func_id;
  830. }};
  831. const auto define{
  832. [&](DefPtr ssbo_member, const StorageTypeDefinition& type_def, Id type, size_t size) {
  833. const Id element_type{type_def.element};
  834. const u32 shift{static_cast<u32>(std::countr_zero(size))};
  835. const Id load_func{define_load(ssbo_member, element_type, type, shift)};
  836. const Id write_func{define_write(ssbo_member, element_type, type, shift)};
  837. return std::make_pair(load_func, write_func);
  838. }};
  839. std::tie(load_global_func_u32, write_global_func_u32) =
  840. define(&StorageDefinitions::U32, storage_types.U32, U32[1], sizeof(u32));
  841. std::tie(load_global_func_u32x2, write_global_func_u32x2) =
  842. define(&StorageDefinitions::U32x2, storage_types.U32x2, U32[2], sizeof(u32[2]));
  843. std::tie(load_global_func_u32x4, write_global_func_u32x4) =
  844. define(&StorageDefinitions::U32x4, storage_types.U32x4, U32[4], sizeof(u32[4]));
  845. }
  846. void EmitContext::DefineRescalingInput(const Info& info) {
  847. if (!info.uses_rescaling_uniform) {
  848. return;
  849. }
  850. if (profile.unified_descriptor_binding) {
  851. DefineRescalingInputPushConstant();
  852. } else {
  853. DefineRescalingInputUniformConstant();
  854. }
  855. }
  856. void EmitContext::DefineRescalingInputPushConstant() {
  857. boost::container::static_vector<Id, 3> members{};
  858. u32 member_index{0};
  859. rescaling_textures_type = TypeArray(U32[1], Const(4u));
  860. Decorate(rescaling_textures_type, spv::Decoration::ArrayStride, 4u);
  861. members.push_back(rescaling_textures_type);
  862. rescaling_textures_member_index = member_index++;
  863. rescaling_images_type = TypeArray(U32[1], Const(NUM_IMAGE_SCALING_WORDS));
  864. Decorate(rescaling_images_type, spv::Decoration::ArrayStride, 4u);
  865. members.push_back(rescaling_images_type);
  866. rescaling_images_member_index = member_index++;
  867. if (stage != Stage::Compute) {
  868. members.push_back(F32[1]);
  869. rescaling_downfactor_member_index = member_index++;
  870. }
  871. const Id push_constant_struct{TypeStruct(std::span(members.data(), members.size()))};
  872. Decorate(push_constant_struct, spv::Decoration::Block);
  873. Name(push_constant_struct, "ResolutionInfo");
  874. MemberDecorate(push_constant_struct, rescaling_textures_member_index, spv::Decoration::Offset,
  875. static_cast<u32>(offsetof(RescalingLayout, rescaling_textures)));
  876. MemberName(push_constant_struct, rescaling_textures_member_index, "rescaling_textures");
  877. MemberDecorate(push_constant_struct, rescaling_images_member_index, spv::Decoration::Offset,
  878. static_cast<u32>(offsetof(RescalingLayout, rescaling_images)));
  879. MemberName(push_constant_struct, rescaling_images_member_index, "rescaling_images");
  880. if (stage != Stage::Compute) {
  881. MemberDecorate(push_constant_struct, rescaling_downfactor_member_index,
  882. spv::Decoration::Offset,
  883. static_cast<u32>(offsetof(RescalingLayout, down_factor)));
  884. MemberName(push_constant_struct, rescaling_downfactor_member_index, "down_factor");
  885. }
  886. const Id pointer_type{TypePointer(spv::StorageClass::PushConstant, push_constant_struct)};
  887. rescaling_push_constants = AddGlobalVariable(pointer_type, spv::StorageClass::PushConstant);
  888. Name(rescaling_push_constants, "rescaling_push_constants");
  889. if (profile.supported_spirv >= 0x00010400) {
  890. interfaces.push_back(rescaling_push_constants);
  891. }
  892. }
  893. void EmitContext::DefineRescalingInputUniformConstant() {
  894. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, F32[4])};
  895. rescaling_uniform_constant =
  896. AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant);
  897. Decorate(rescaling_uniform_constant, spv::Decoration::Location, 0u);
  898. if (profile.supported_spirv >= 0x00010400) {
  899. interfaces.push_back(rescaling_uniform_constant);
  900. }
  901. }
  902. void EmitContext::DefineConstantBuffers(const Info& info, u32& binding) {
  903. if (info.constant_buffer_descriptors.empty()) {
  904. return;
  905. }
  906. if (!profile.support_descriptor_aliasing) {
  907. DefineConstBuffers(*this, info, &UniformDefinitions::U32x4, binding, U32[4], 'u',
  908. sizeof(u32[4]));
  909. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  910. binding += desc.count;
  911. }
  912. return;
  913. }
  914. IR::Type types{info.used_constant_buffer_types | info.used_indirect_cbuf_types};
  915. if (True(types & IR::Type::U8)) {
  916. if (profile.support_int8) {
  917. DefineConstBuffers(*this, info, &UniformDefinitions::U8, binding, U8, 'u', sizeof(u8));
  918. DefineConstBuffers(*this, info, &UniformDefinitions::S8, binding, S8, 's', sizeof(s8));
  919. } else {
  920. types |= IR::Type::U32;
  921. }
  922. }
  923. if (True(types & IR::Type::U16)) {
  924. if (profile.support_int16) {
  925. DefineConstBuffers(*this, info, &UniformDefinitions::U16, binding, U16, 'u',
  926. sizeof(u16));
  927. DefineConstBuffers(*this, info, &UniformDefinitions::S16, binding, S16, 's',
  928. sizeof(s16));
  929. } else {
  930. types |= IR::Type::U32;
  931. }
  932. }
  933. if (True(types & IR::Type::U32)) {
  934. DefineConstBuffers(*this, info, &UniformDefinitions::U32, binding, U32[1], 'u',
  935. sizeof(u32));
  936. }
  937. if (True(types & IR::Type::F32)) {
  938. DefineConstBuffers(*this, info, &UniformDefinitions::F32, binding, F32[1], 'f',
  939. sizeof(f32));
  940. }
  941. if (True(types & IR::Type::U32x2)) {
  942. DefineConstBuffers(*this, info, &UniformDefinitions::U32x2, binding, U32[2], 'u',
  943. sizeof(u32[2]));
  944. }
  945. binding += static_cast<u32>(info.constant_buffer_descriptors.size());
  946. }
  947. void EmitContext::DefineConstantBufferIndirectFunctions(const Info& info) {
  948. if (!info.uses_cbuf_indirect) {
  949. return;
  950. }
  951. const auto make_accessor{[&](Id buffer_type, Id UniformDefinitions::*member_ptr) {
  952. const Id func_type{TypeFunction(buffer_type, U32[1], U32[1])};
  953. const Id func{OpFunction(buffer_type, spv::FunctionControlMask::MaskNone, func_type)};
  954. const Id binding{OpFunctionParameter(U32[1])};
  955. const Id offset{OpFunctionParameter(U32[1])};
  956. AddLabel();
  957. const Id merge_label{OpLabel()};
  958. const Id uniform_type{uniform_types.*member_ptr};
  959. std::array<Id, Info::MAX_INDIRECT_CBUFS> buf_labels;
  960. std::array<Sirit::Literal, Info::MAX_INDIRECT_CBUFS> buf_literals;
  961. for (u32 i = 0; i < Info::MAX_INDIRECT_CBUFS; i++) {
  962. buf_labels[i] = OpLabel();
  963. buf_literals[i] = Sirit::Literal{i};
  964. }
  965. OpSelectionMerge(merge_label, spv::SelectionControlMask::MaskNone);
  966. OpSwitch(binding, buf_labels[0], buf_literals, buf_labels);
  967. for (u32 i = 0; i < Info::MAX_INDIRECT_CBUFS; i++) {
  968. AddLabel(buf_labels[i]);
  969. const Id cbuf{cbufs[i].*member_ptr};
  970. const Id access_chain{OpAccessChain(uniform_type, cbuf, u32_zero_value, offset)};
  971. const Id result{OpLoad(buffer_type, access_chain)};
  972. OpReturnValue(result);
  973. }
  974. AddLabel(merge_label);
  975. OpUnreachable();
  976. OpFunctionEnd();
  977. return func;
  978. }};
  979. IR::Type types{info.used_indirect_cbuf_types};
  980. bool supports_aliasing = profile.support_descriptor_aliasing;
  981. if (supports_aliasing && True(types & IR::Type::U8)) {
  982. load_const_func_u8 = make_accessor(U8, &UniformDefinitions::U8);
  983. }
  984. if (supports_aliasing && True(types & IR::Type::U16)) {
  985. load_const_func_u16 = make_accessor(U16, &UniformDefinitions::U16);
  986. }
  987. if (supports_aliasing && True(types & IR::Type::F32)) {
  988. load_const_func_f32 = make_accessor(F32[1], &UniformDefinitions::F32);
  989. }
  990. if (supports_aliasing && True(types & IR::Type::U32)) {
  991. load_const_func_u32 = make_accessor(U32[1], &UniformDefinitions::U32);
  992. }
  993. if (supports_aliasing && True(types & IR::Type::U32x2)) {
  994. load_const_func_u32x2 = make_accessor(U32[2], &UniformDefinitions::U32x2);
  995. }
  996. if (!supports_aliasing || True(types & IR::Type::U32x4)) {
  997. load_const_func_u32x4 = make_accessor(U32[4], &UniformDefinitions::U32x4);
  998. }
  999. }
  1000. void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
  1001. if (info.storage_buffers_descriptors.empty()) {
  1002. return;
  1003. }
  1004. AddExtension("SPV_KHR_storage_buffer_storage_class");
  1005. const IR::Type used_types{profile.support_descriptor_aliasing ? info.used_storage_buffer_types
  1006. : IR::Type::U32};
  1007. if (profile.support_int8 && True(used_types & IR::Type::U8)) {
  1008. DefineSsbos(*this, storage_types.U8, &StorageDefinitions::U8, info, binding, U8,
  1009. sizeof(u8));
  1010. DefineSsbos(*this, storage_types.S8, &StorageDefinitions::S8, info, binding, S8,
  1011. sizeof(u8));
  1012. }
  1013. if (profile.support_int16 && True(used_types & IR::Type::U16)) {
  1014. DefineSsbos(*this, storage_types.U16, &StorageDefinitions::U16, info, binding, U16,
  1015. sizeof(u16));
  1016. DefineSsbos(*this, storage_types.S16, &StorageDefinitions::S16, info, binding, S16,
  1017. sizeof(u16));
  1018. }
  1019. if (True(used_types & IR::Type::U32)) {
  1020. DefineSsbos(*this, storage_types.U32, &StorageDefinitions::U32, info, binding, U32[1],
  1021. sizeof(u32));
  1022. }
  1023. if (True(used_types & IR::Type::F32)) {
  1024. DefineSsbos(*this, storage_types.F32, &StorageDefinitions::F32, info, binding, F32[1],
  1025. sizeof(f32));
  1026. }
  1027. if (True(used_types & IR::Type::U64)) {
  1028. DefineSsbos(*this, storage_types.U64, &StorageDefinitions::U64, info, binding, U64,
  1029. sizeof(u64));
  1030. }
  1031. if (True(used_types & IR::Type::U32x2)) {
  1032. DefineSsbos(*this, storage_types.U32x2, &StorageDefinitions::U32x2, info, binding, U32[2],
  1033. sizeof(u32[2]));
  1034. }
  1035. if (True(used_types & IR::Type::U32x4)) {
  1036. DefineSsbos(*this, storage_types.U32x4, &StorageDefinitions::U32x4, info, binding, U32[4],
  1037. sizeof(u32[4]));
  1038. }
  1039. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  1040. binding += desc.count;
  1041. }
  1042. const bool needs_function{
  1043. info.uses_global_increment || info.uses_global_decrement || info.uses_atomic_f32_add ||
  1044. info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max ||
  1045. info.uses_atomic_f32x2_add || info.uses_atomic_f32x2_min || info.uses_atomic_f32x2_max};
  1046. if (needs_function) {
  1047. AddCapability(spv::Capability::VariablePointersStorageBuffer);
  1048. }
  1049. if (info.uses_global_increment) {
  1050. increment_cas_ssbo = CasLoop(*this, Operation::Increment, storage_types.U32.array,
  1051. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  1052. }
  1053. if (info.uses_global_decrement) {
  1054. decrement_cas_ssbo = CasLoop(*this, Operation::Decrement, storage_types.U32.array,
  1055. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  1056. }
  1057. if (info.uses_atomic_f32_add) {
  1058. f32_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  1059. storage_types.U32.element, F32[1], U32[1], spv::Scope::Device);
  1060. }
  1061. if (info.uses_atomic_f16x2_add) {
  1062. f16x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  1063. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  1064. }
  1065. if (info.uses_atomic_f16x2_min) {
  1066. f16x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  1067. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  1068. }
  1069. if (info.uses_atomic_f16x2_max) {
  1070. f16x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  1071. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  1072. }
  1073. if (info.uses_atomic_f32x2_add) {
  1074. f32x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  1075. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  1076. }
  1077. if (info.uses_atomic_f32x2_min) {
  1078. f32x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  1079. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  1080. }
  1081. if (info.uses_atomic_f32x2_max) {
  1082. f32x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  1083. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  1084. }
  1085. }
  1086. void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) {
  1087. if (info.texture_buffer_descriptors.empty()) {
  1088. return;
  1089. }
  1090. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  1091. image_buffer_type = TypeImage(F32[1], spv::Dim::Buffer, 0U, false, false, 1, format);
  1092. sampled_texture_buffer_type = TypeSampledImage(image_buffer_type);
  1093. const Id type{TypePointer(spv::StorageClass::UniformConstant, sampled_texture_buffer_type)};
  1094. texture_buffers.reserve(info.texture_buffer_descriptors.size());
  1095. for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) {
  1096. if (desc.count != 1) {
  1097. throw NotImplementedException("Array of texture buffers");
  1098. }
  1099. const Id id{AddGlobalVariable(type, spv::StorageClass::UniformConstant)};
  1100. Decorate(id, spv::Decoration::Binding, binding);
  1101. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1102. Name(id, NameOf(stage, desc, "texbuf"));
  1103. texture_buffers.push_back({
  1104. .id = id,
  1105. .count = desc.count,
  1106. });
  1107. if (profile.supported_spirv >= 0x00010400) {
  1108. interfaces.push_back(id);
  1109. }
  1110. ++binding;
  1111. }
  1112. }
  1113. void EmitContext::DefineImageBuffers(const Info& info, u32& binding) {
  1114. image_buffers.reserve(info.image_buffer_descriptors.size());
  1115. for (const ImageBufferDescriptor& desc : info.image_buffer_descriptors) {
  1116. if (desc.count != 1) {
  1117. throw NotImplementedException("Array of image buffers");
  1118. }
  1119. const spv::ImageFormat format{GetImageFormat(desc.format)};
  1120. const Id image_type{TypeImage(U32[1], spv::Dim::Buffer, false, false, false, 2, format)};
  1121. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1122. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1123. Decorate(id, spv::Decoration::Binding, binding);
  1124. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1125. Name(id, NameOf(stage, desc, "imgbuf"));
  1126. image_buffers.push_back({
  1127. .id = id,
  1128. .image_type = image_type,
  1129. .count = desc.count,
  1130. });
  1131. if (profile.supported_spirv >= 0x00010400) {
  1132. interfaces.push_back(id);
  1133. }
  1134. ++binding;
  1135. }
  1136. }
  1137. void EmitContext::DefineTextures(const Info& info, u32& binding, u32& scaling_index) {
  1138. textures.reserve(info.texture_descriptors.size());
  1139. for (const TextureDescriptor& desc : info.texture_descriptors) {
  1140. const Id image_type{ImageType(*this, desc)};
  1141. const Id sampled_type{TypeSampledImage(image_type)};
  1142. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, sampled_type)};
  1143. const Id desc_type{DescType(*this, sampled_type, pointer_type, desc.count)};
  1144. const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
  1145. Decorate(id, spv::Decoration::Binding, binding);
  1146. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1147. Name(id, NameOf(stage, desc, "tex"));
  1148. textures.push_back({
  1149. .id = id,
  1150. .sampled_type = sampled_type,
  1151. .pointer_type = pointer_type,
  1152. .image_type = image_type,
  1153. .count = desc.count,
  1154. });
  1155. if (profile.supported_spirv >= 0x00010400) {
  1156. interfaces.push_back(id);
  1157. }
  1158. ++binding;
  1159. ++scaling_index;
  1160. }
  1161. if (info.uses_atomic_image_u32) {
  1162. image_u32 = TypePointer(spv::StorageClass::Image, U32[1]);
  1163. }
  1164. }
  1165. void EmitContext::DefineImages(const Info& info, u32& binding, u32& scaling_index) {
  1166. images.reserve(info.image_descriptors.size());
  1167. for (const ImageDescriptor& desc : info.image_descriptors) {
  1168. if (desc.count != 1) {
  1169. throw NotImplementedException("Array of images");
  1170. }
  1171. const Id image_type{ImageType(*this, desc)};
  1172. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1173. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1174. Decorate(id, spv::Decoration::Binding, binding);
  1175. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1176. Name(id, NameOf(stage, desc, "img"));
  1177. images.push_back({
  1178. .id = id,
  1179. .image_type = image_type,
  1180. .count = desc.count,
  1181. });
  1182. if (profile.supported_spirv >= 0x00010400) {
  1183. interfaces.push_back(id);
  1184. }
  1185. ++binding;
  1186. ++scaling_index;
  1187. }
  1188. }
  1189. void EmitContext::DefineInputs(const IR::Program& program) {
  1190. const Info& info{program.info};
  1191. const VaryingState loads{info.loads.mask | info.passthrough.mask};
  1192. if (info.uses_workgroup_id) {
  1193. workgroup_id = DefineInput(*this, U32[3], false, spv::BuiltIn::WorkgroupId);
  1194. }
  1195. if (info.uses_local_invocation_id) {
  1196. local_invocation_id = DefineInput(*this, U32[3], false, spv::BuiltIn::LocalInvocationId);
  1197. }
  1198. if (info.uses_invocation_id) {
  1199. invocation_id = DefineInput(*this, U32[1], false, spv::BuiltIn::InvocationId);
  1200. }
  1201. if (info.uses_sample_id) {
  1202. sample_id = DefineInput(*this, U32[1], false, spv::BuiltIn::SampleId);
  1203. }
  1204. if (info.uses_is_helper_invocation) {
  1205. is_helper_invocation = DefineInput(*this, U1, false, spv::BuiltIn::HelperInvocation);
  1206. }
  1207. if (info.uses_subgroup_mask) {
  1208. subgroup_mask_eq = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupEqMaskKHR);
  1209. subgroup_mask_lt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLtMaskKHR);
  1210. subgroup_mask_le = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLeMaskKHR);
  1211. subgroup_mask_gt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGtMaskKHR);
  1212. subgroup_mask_ge = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGeMaskKHR);
  1213. }
  1214. if (info.uses_subgroup_invocation_id || info.uses_subgroup_shuffles ||
  1215. (profile.warp_size_potentially_larger_than_guest &&
  1216. (info.uses_subgroup_vote || info.uses_subgroup_mask))) {
  1217. subgroup_local_invocation_id =
  1218. DefineInput(*this, U32[1], false, spv::BuiltIn::SubgroupLocalInvocationId);
  1219. }
  1220. if (info.uses_fswzadd) {
  1221. const Id f32_one{Const(1.0f)};
  1222. const Id f32_minus_one{Const(-1.0f)};
  1223. const Id f32_zero{Const(0.0f)};
  1224. fswzadd_lut_a = ConstantComposite(F32[4], f32_minus_one, f32_one, f32_minus_one, f32_zero);
  1225. fswzadd_lut_b =
  1226. ConstantComposite(F32[4], f32_minus_one, f32_minus_one, f32_one, f32_minus_one);
  1227. }
  1228. if (loads[IR::Attribute::PrimitiveId]) {
  1229. primitive_id = DefineInput(*this, U32[1], false, spv::BuiltIn::PrimitiveId);
  1230. }
  1231. if (loads.AnyComponent(IR::Attribute::PositionX)) {
  1232. const bool is_fragment{stage != Stage::Fragment};
  1233. const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
  1234. input_position = DefineInput(*this, F32[4], true, built_in);
  1235. if (profile.support_geometry_shader_passthrough) {
  1236. if (info.passthrough.AnyComponent(IR::Attribute::PositionX)) {
  1237. Decorate(input_position, spv::Decoration::PassthroughNV);
  1238. }
  1239. }
  1240. }
  1241. if (loads[IR::Attribute::InstanceId]) {
  1242. if (profile.support_vertex_instance_id) {
  1243. instance_id = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceId);
  1244. } else {
  1245. instance_index = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceIndex);
  1246. base_instance = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseInstance);
  1247. }
  1248. }
  1249. if (loads[IR::Attribute::VertexId]) {
  1250. if (profile.support_vertex_instance_id) {
  1251. vertex_id = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexId);
  1252. } else {
  1253. vertex_index = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexIndex);
  1254. base_vertex = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseVertex);
  1255. }
  1256. }
  1257. if (loads[IR::Attribute::FrontFace]) {
  1258. front_face = DefineInput(*this, U1, true, spv::BuiltIn::FrontFacing);
  1259. }
  1260. if (loads[IR::Attribute::PointSpriteS] || loads[IR::Attribute::PointSpriteT]) {
  1261. point_coord = DefineInput(*this, F32[2], true, spv::BuiltIn::PointCoord);
  1262. }
  1263. if (loads[IR::Attribute::TessellationEvaluationPointU] ||
  1264. loads[IR::Attribute::TessellationEvaluationPointV]) {
  1265. tess_coord = DefineInput(*this, F32[3], false, spv::BuiltIn::TessCoord);
  1266. }
  1267. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  1268. const AttributeType input_type{runtime_info.generic_input_types[index]};
  1269. if (!runtime_info.previous_stage_stores.Generic(index)) {
  1270. continue;
  1271. }
  1272. if (!loads.Generic(index)) {
  1273. continue;
  1274. }
  1275. if (input_type == AttributeType::Disabled) {
  1276. continue;
  1277. }
  1278. const Id type{GetAttributeType(*this, input_type)};
  1279. const Id id{DefineInput(*this, type, true)};
  1280. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1281. Name(id, fmt::format("in_attr{}", index));
  1282. input_generics[index] = id;
  1283. if (info.passthrough.Generic(index) && profile.support_geometry_shader_passthrough) {
  1284. Decorate(id, spv::Decoration::PassthroughNV);
  1285. }
  1286. if (stage != Stage::Fragment) {
  1287. continue;
  1288. }
  1289. switch (info.interpolation[index]) {
  1290. case Interpolation::Smooth:
  1291. // Default
  1292. // Decorate(id, spv::Decoration::Smooth);
  1293. break;
  1294. case Interpolation::NoPerspective:
  1295. Decorate(id, spv::Decoration::NoPerspective);
  1296. break;
  1297. case Interpolation::Flat:
  1298. Decorate(id, spv::Decoration::Flat);
  1299. break;
  1300. }
  1301. }
  1302. if (stage == Stage::TessellationEval) {
  1303. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1304. if (!info.uses_patches[index]) {
  1305. continue;
  1306. }
  1307. const Id id{DefineInput(*this, F32[4], false)};
  1308. Decorate(id, spv::Decoration::Patch);
  1309. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1310. patches[index] = id;
  1311. }
  1312. }
  1313. }
  1314. void EmitContext::DefineOutputs(const IR::Program& program) {
  1315. const Info& info{program.info};
  1316. const std::optional<u32> invocations{program.invocations};
  1317. if (info.stores.AnyComponent(IR::Attribute::PositionX) || stage == Stage::VertexB) {
  1318. output_position = DefineOutput(*this, F32[4], invocations, spv::BuiltIn::Position);
  1319. }
  1320. if (info.stores[IR::Attribute::PointSize] || runtime_info.fixed_state_point_size) {
  1321. if (stage == Stage::Fragment) {
  1322. throw NotImplementedException("Storing PointSize in fragment stage");
  1323. }
  1324. output_point_size = DefineOutput(*this, F32[1], invocations, spv::BuiltIn::PointSize);
  1325. }
  1326. if (info.stores.ClipDistances()) {
  1327. if (stage == Stage::Fragment) {
  1328. throw NotImplementedException("Storing ClipDistance in fragment stage");
  1329. }
  1330. const Id type{TypeArray(F32[1], Const(8U))};
  1331. clip_distances = DefineOutput(*this, type, invocations, spv::BuiltIn::ClipDistance);
  1332. }
  1333. if (info.stores[IR::Attribute::Layer] &&
  1334. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1335. if (stage == Stage::Fragment) {
  1336. throw NotImplementedException("Storing Layer in fragment stage");
  1337. }
  1338. layer = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::Layer);
  1339. }
  1340. if (info.stores[IR::Attribute::ViewportIndex] &&
  1341. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1342. if (stage == Stage::Fragment) {
  1343. throw NotImplementedException("Storing ViewportIndex in fragment stage");
  1344. }
  1345. viewport_index = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::ViewportIndex);
  1346. }
  1347. if (info.stores[IR::Attribute::ViewportMask] && profile.support_viewport_mask) {
  1348. viewport_mask = DefineOutput(*this, TypeArray(U32[1], Const(1u)), std::nullopt,
  1349. spv::BuiltIn::ViewportMaskNV);
  1350. }
  1351. for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
  1352. if (info.stores.Generic(index)) {
  1353. DefineGenericOutput(*this, index, invocations);
  1354. }
  1355. }
  1356. switch (stage) {
  1357. case Stage::TessellationControl:
  1358. if (info.stores_tess_level_outer) {
  1359. const Id type{TypeArray(F32[1], Const(4U))};
  1360. output_tess_level_outer =
  1361. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelOuter);
  1362. Decorate(output_tess_level_outer, spv::Decoration::Patch);
  1363. }
  1364. if (info.stores_tess_level_inner) {
  1365. const Id type{TypeArray(F32[1], Const(2U))};
  1366. output_tess_level_inner =
  1367. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelInner);
  1368. Decorate(output_tess_level_inner, spv::Decoration::Patch);
  1369. }
  1370. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1371. if (!info.uses_patches[index]) {
  1372. continue;
  1373. }
  1374. const Id id{DefineOutput(*this, F32[4], std::nullopt)};
  1375. Decorate(id, spv::Decoration::Patch);
  1376. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1377. patches[index] = id;
  1378. }
  1379. break;
  1380. case Stage::Fragment:
  1381. for (u32 index = 0; index < 8; ++index) {
  1382. if (!info.stores_frag_color[index] && !profile.need_declared_frag_colors) {
  1383. continue;
  1384. }
  1385. frag_color[index] = DefineOutput(*this, F32[4], std::nullopt);
  1386. Decorate(frag_color[index], spv::Decoration::Location, index);
  1387. Name(frag_color[index], fmt::format("frag_color{}", index));
  1388. }
  1389. if (info.stores_frag_depth) {
  1390. frag_depth = DefineOutput(*this, F32[1], std::nullopt);
  1391. Decorate(frag_depth, spv::Decoration::BuiltIn, spv::BuiltIn::FragDepth);
  1392. }
  1393. if (info.stores_sample_mask) {
  1394. sample_mask = DefineOutput(*this, U32[1], std::nullopt);
  1395. Decorate(sample_mask, spv::Decoration::BuiltIn, spv::BuiltIn::SampleMask);
  1396. }
  1397. break;
  1398. default:
  1399. break;
  1400. }
  1401. }
  1402. } // namespace Shader::Backend::SPIRV