Declarations.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.StructuredIr;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using Spv.Generator;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using static Spv.Specification;
  10. namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
  11. {
  12. using SpvInstruction = Spv.Generator.Instruction;
  13. static class Declarations
  14. {
  15. // At least 16 attributes are guaranteed by the spec.
  16. public const int MaxAttributes = 16;
  17. private static readonly string[] StagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
  18. public static void DeclareParameters(CodeGenContext context, StructuredFunction function)
  19. {
  20. DeclareParameters(context, function.InArguments, 0);
  21. DeclareParameters(context, function.OutArguments, function.InArguments.Length);
  22. }
  23. private static void DeclareParameters(CodeGenContext context, IEnumerable<VariableType> argTypes, int argIndex)
  24. {
  25. foreach (var argType in argTypes)
  26. {
  27. var argPointerType = context.TypePointer(StorageClass.Function, context.GetType(argType.Convert()));
  28. var spvArg = context.FunctionParameter(argPointerType);
  29. context.DeclareArgument(argIndex++, spvArg);
  30. }
  31. }
  32. public static void DeclareLocals(CodeGenContext context, StructuredFunction function)
  33. {
  34. foreach (AstOperand local in function.Locals)
  35. {
  36. var localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType.Convert()));
  37. var spvLocal = context.Variable(localPointerType, StorageClass.Function);
  38. context.AddLocalVariable(spvLocal);
  39. context.DeclareLocal(local, spvLocal);
  40. }
  41. var ivector2Type = context.TypeVector(context.TypeS32(), 2);
  42. var coordTempPointerType = context.TypePointer(StorageClass.Function, ivector2Type);
  43. var coordTemp = context.Variable(coordTempPointerType, StorageClass.Function);
  44. context.AddLocalVariable(coordTemp);
  45. context.CoordTemp = coordTemp;
  46. }
  47. public static void DeclareLocalForArgs(CodeGenContext context, List<StructuredFunction> functions)
  48. {
  49. for (int funcIndex = 0; funcIndex < functions.Count; funcIndex++)
  50. {
  51. StructuredFunction function = functions[funcIndex];
  52. SpvInstruction[] locals = new SpvInstruction[function.InArguments.Length];
  53. for (int i = 0; i < function.InArguments.Length; i++)
  54. {
  55. var type = function.GetArgumentType(i).Convert();
  56. var localPointerType = context.TypePointer(StorageClass.Function, context.GetType(type));
  57. var spvLocal = context.Variable(localPointerType, StorageClass.Function);
  58. context.AddLocalVariable(spvLocal);
  59. locals[i] = spvLocal;
  60. }
  61. context.DeclareLocalForArgs(funcIndex, locals);
  62. }
  63. }
  64. public static void DeclareAll(CodeGenContext context, StructuredProgramInfo info)
  65. {
  66. if (context.Config.Stage == ShaderStage.Compute)
  67. {
  68. int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
  69. if (localMemorySize != 0)
  70. {
  71. DeclareLocalMemory(context, localMemorySize);
  72. }
  73. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
  74. if (sharedMemorySize != 0)
  75. {
  76. DeclareSharedMemory(context, sharedMemorySize);
  77. }
  78. }
  79. else if (context.Config.LocalMemorySize != 0)
  80. {
  81. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  82. DeclareLocalMemory(context, localMemorySize);
  83. }
  84. DeclareSupportBuffer(context);
  85. DeclareUniformBuffers(context, context.Config.GetConstantBufferDescriptors());
  86. DeclareStorageBuffers(context, context.Config.GetStorageBufferDescriptors());
  87. DeclareSamplers(context, context.Config.GetTextureDescriptors());
  88. DeclareImages(context, context.Config.GetImageDescriptors());
  89. DeclareInputAttributes(context, info, perPatch: false);
  90. DeclareOutputAttributes(context, info, perPatch: false);
  91. DeclareInputAttributes(context, info, perPatch: true);
  92. DeclareOutputAttributes(context, info, perPatch: true);
  93. }
  94. private static void DeclareLocalMemory(CodeGenContext context, int size)
  95. {
  96. context.LocalMemory = DeclareMemory(context, StorageClass.Private, size);
  97. }
  98. private static void DeclareSharedMemory(CodeGenContext context, int size)
  99. {
  100. context.SharedMemory = DeclareMemory(context, StorageClass.Workgroup, size);
  101. }
  102. private static SpvInstruction DeclareMemory(CodeGenContext context, StorageClass storage, int size)
  103. {
  104. var arrayType = context.TypeArray(context.TypeU32(), context.Constant(context.TypeU32(), size));
  105. var pointerType = context.TypePointer(storage, arrayType);
  106. var variable = context.Variable(pointerType, storage);
  107. context.AddGlobalVariable(variable);
  108. return variable;
  109. }
  110. private static void DeclareSupportBuffer(CodeGenContext context)
  111. {
  112. if (!context.Config.Stage.SupportsRenderScale() && !(context.Config.LastInVertexPipeline && context.Config.GpuAccessor.QueryViewportTransformDisable()))
  113. {
  114. return;
  115. }
  116. var isBgraArrayType = context.TypeArray(context.TypeU32(), context.Constant(context.TypeU32(), SupportBuffer.FragmentIsBgraCount));
  117. var viewportInverseVectorType = context.TypeVector(context.TypeFP32(), 4);
  118. var renderScaleArrayType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), SupportBuffer.RenderScaleMaxCount));
  119. context.Decorate(isBgraArrayType, Decoration.ArrayStride, (LiteralInteger)SupportBuffer.FieldSize);
  120. context.Decorate(renderScaleArrayType, Decoration.ArrayStride, (LiteralInteger)SupportBuffer.FieldSize);
  121. var supportBufferStructType = context.TypeStruct(false, context.TypeU32(), isBgraArrayType, viewportInverseVectorType, context.TypeS32(), renderScaleArrayType);
  122. context.MemberDecorate(supportBufferStructType, 0, Decoration.Offset, (LiteralInteger)SupportBuffer.FragmentAlphaTestOffset);
  123. context.MemberDecorate(supportBufferStructType, 1, Decoration.Offset, (LiteralInteger)SupportBuffer.FragmentIsBgraOffset);
  124. context.MemberDecorate(supportBufferStructType, 2, Decoration.Offset, (LiteralInteger)SupportBuffer.ViewportInverseOffset);
  125. context.MemberDecorate(supportBufferStructType, 3, Decoration.Offset, (LiteralInteger)SupportBuffer.FragmentRenderScaleCountOffset);
  126. context.MemberDecorate(supportBufferStructType, 4, Decoration.Offset, (LiteralInteger)SupportBuffer.GraphicsRenderScaleOffset);
  127. context.Decorate(supportBufferStructType, Decoration.Block);
  128. var supportBufferPointerType = context.TypePointer(StorageClass.Uniform, supportBufferStructType);
  129. var supportBufferVariable = context.Variable(supportBufferPointerType, StorageClass.Uniform);
  130. context.Decorate(supportBufferVariable, Decoration.DescriptorSet, (LiteralInteger)0);
  131. context.Decorate(supportBufferVariable, Decoration.Binding, (LiteralInteger)0);
  132. context.AddGlobalVariable(supportBufferVariable);
  133. context.SupportBuffer = supportBufferVariable;
  134. }
  135. private static void DeclareUniformBuffers(CodeGenContext context, BufferDescriptor[] descriptors)
  136. {
  137. if (descriptors.Length == 0)
  138. {
  139. return;
  140. }
  141. uint ubSize = Constants.ConstantBufferSize / 16;
  142. var ubArrayType = context.TypeArray(context.TypeVector(context.TypeFP32(), 4), context.Constant(context.TypeU32(), ubSize), true);
  143. context.Decorate(ubArrayType, Decoration.ArrayStride, (LiteralInteger)16);
  144. var ubStructType = context.TypeStruct(true, ubArrayType);
  145. context.Decorate(ubStructType, Decoration.Block);
  146. context.MemberDecorate(ubStructType, 0, Decoration.Offset, (LiteralInteger)0);
  147. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  148. {
  149. int count = descriptors.Max(x => x.Slot) + 1;
  150. var ubStructArrayType = context.TypeArray(ubStructType, context.Constant(context.TypeU32(), count));
  151. var ubPointerType = context.TypePointer(StorageClass.Uniform, ubStructArrayType);
  152. var ubVariable = context.Variable(ubPointerType, StorageClass.Uniform);
  153. context.Name(ubVariable, $"{GetStagePrefix(context.Config.Stage)}_u");
  154. context.Decorate(ubVariable, Decoration.DescriptorSet, (LiteralInteger)0);
  155. context.Decorate(ubVariable, Decoration.Binding, (LiteralInteger)context.Config.FirstConstantBufferBinding);
  156. context.AddGlobalVariable(ubVariable);
  157. context.UniformBuffersArray = ubVariable;
  158. }
  159. else
  160. {
  161. var ubPointerType = context.TypePointer(StorageClass.Uniform, ubStructType);
  162. foreach (var descriptor in descriptors)
  163. {
  164. var ubVariable = context.Variable(ubPointerType, StorageClass.Uniform);
  165. context.Name(ubVariable, $"{GetStagePrefix(context.Config.Stage)}_c{descriptor.Slot}");
  166. context.Decorate(ubVariable, Decoration.DescriptorSet, (LiteralInteger)0);
  167. context.Decorate(ubVariable, Decoration.Binding, (LiteralInteger)descriptor.Binding);
  168. context.AddGlobalVariable(ubVariable);
  169. context.UniformBuffers.Add(descriptor.Slot, ubVariable);
  170. }
  171. }
  172. }
  173. private static void DeclareStorageBuffers(CodeGenContext context, BufferDescriptor[] descriptors)
  174. {
  175. if (descriptors.Length == 0)
  176. {
  177. return;
  178. }
  179. int setIndex = context.Config.Options.TargetApi == TargetApi.Vulkan ? 1 : 0;
  180. int count = descriptors.Max(x => x.Slot) + 1;
  181. var sbArrayType = context.TypeRuntimeArray(context.TypeU32());
  182. context.Decorate(sbArrayType, Decoration.ArrayStride, (LiteralInteger)4);
  183. var sbStructType = context.TypeStruct(true, sbArrayType);
  184. context.Decorate(sbStructType, Decoration.BufferBlock);
  185. context.MemberDecorate(sbStructType, 0, Decoration.Offset, (LiteralInteger)0);
  186. var sbStructArrayType = context.TypeArray(sbStructType, context.Constant(context.TypeU32(), count));
  187. var sbPointerType = context.TypePointer(StorageClass.Uniform, sbStructArrayType);
  188. var sbVariable = context.Variable(sbPointerType, StorageClass.Uniform);
  189. context.Name(sbVariable, $"{GetStagePrefix(context.Config.Stage)}_s");
  190. context.Decorate(sbVariable, Decoration.DescriptorSet, (LiteralInteger)setIndex);
  191. context.Decorate(sbVariable, Decoration.Binding, (LiteralInteger)context.Config.FirstStorageBufferBinding);
  192. context.AddGlobalVariable(sbVariable);
  193. context.StorageBuffersArray = sbVariable;
  194. }
  195. private static void DeclareSamplers(CodeGenContext context, TextureDescriptor[] descriptors)
  196. {
  197. foreach (var descriptor in descriptors)
  198. {
  199. var meta = new TextureMeta(descriptor.CbufSlot, descriptor.HandleIndex, descriptor.Format);
  200. if (context.Samplers.ContainsKey(meta))
  201. {
  202. continue;
  203. }
  204. int setIndex = context.Config.Options.TargetApi == TargetApi.Vulkan ? 2 : 0;
  205. var dim = (descriptor.Type & SamplerType.Mask) switch
  206. {
  207. SamplerType.Texture1D => Dim.Dim1D,
  208. SamplerType.Texture2D => Dim.Dim2D,
  209. SamplerType.Texture3D => Dim.Dim3D,
  210. SamplerType.TextureCube => Dim.Cube,
  211. SamplerType.TextureBuffer => Dim.Buffer,
  212. _ => throw new InvalidOperationException($"Invalid sampler type \"{descriptor.Type & SamplerType.Mask}\".")
  213. };
  214. var imageType = context.TypeImage(
  215. context.TypeFP32(),
  216. dim,
  217. descriptor.Type.HasFlag(SamplerType.Shadow),
  218. descriptor.Type.HasFlag(SamplerType.Array),
  219. descriptor.Type.HasFlag(SamplerType.Multisample),
  220. 1,
  221. ImageFormat.Unknown);
  222. var nameSuffix = meta.CbufSlot < 0 ? $"_tcb_{meta.Handle:X}" : $"_cb{meta.CbufSlot}_{meta.Handle:X}";
  223. var sampledImageType = context.TypeSampledImage(imageType);
  224. var sampledImagePointerType = context.TypePointer(StorageClass.UniformConstant, sampledImageType);
  225. var sampledImageVariable = context.Variable(sampledImagePointerType, StorageClass.UniformConstant);
  226. context.Samplers.Add(meta, (imageType, sampledImageType, sampledImageVariable));
  227. context.SamplersTypes.Add(meta, descriptor.Type);
  228. context.Name(sampledImageVariable, $"{GetStagePrefix(context.Config.Stage)}_tex{nameSuffix}");
  229. context.Decorate(sampledImageVariable, Decoration.DescriptorSet, (LiteralInteger)setIndex);
  230. context.Decorate(sampledImageVariable, Decoration.Binding, (LiteralInteger)descriptor.Binding);
  231. context.AddGlobalVariable(sampledImageVariable);
  232. }
  233. }
  234. private static void DeclareImages(CodeGenContext context, TextureDescriptor[] descriptors)
  235. {
  236. foreach (var descriptor in descriptors)
  237. {
  238. var meta = new TextureMeta(descriptor.CbufSlot, descriptor.HandleIndex, descriptor.Format);
  239. if (context.Images.ContainsKey(meta))
  240. {
  241. continue;
  242. }
  243. int setIndex = context.Config.Options.TargetApi == TargetApi.Vulkan ? 3 : 0;
  244. var dim = GetDim(descriptor.Type);
  245. var imageType = context.TypeImage(
  246. context.GetType(meta.Format.GetComponentType().Convert()),
  247. dim,
  248. descriptor.Type.HasFlag(SamplerType.Shadow),
  249. descriptor.Type.HasFlag(SamplerType.Array),
  250. descriptor.Type.HasFlag(SamplerType.Multisample),
  251. AccessQualifier.ReadWrite,
  252. GetImageFormat(meta.Format));
  253. var nameSuffix = meta.CbufSlot < 0 ?
  254. $"_tcb_{meta.Handle:X}_{meta.Format.ToGlslFormat()}" :
  255. $"_cb{meta.CbufSlot}_{meta.Handle:X}_{meta.Format.ToGlslFormat()}";
  256. var imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType);
  257. var imageVariable = context.Variable(imagePointerType, StorageClass.UniformConstant);
  258. context.Images.Add(meta, (imageType, imageVariable));
  259. context.Name(imageVariable, $"{GetStagePrefix(context.Config.Stage)}_img{nameSuffix}");
  260. context.Decorate(imageVariable, Decoration.DescriptorSet, (LiteralInteger)setIndex);
  261. context.Decorate(imageVariable, Decoration.Binding, (LiteralInteger)descriptor.Binding);
  262. if (descriptor.Flags.HasFlag(TextureUsageFlags.ImageCoherent))
  263. {
  264. context.Decorate(imageVariable, Decoration.Coherent);
  265. }
  266. context.AddGlobalVariable(imageVariable);
  267. }
  268. }
  269. private static Dim GetDim(SamplerType type)
  270. {
  271. return (type & SamplerType.Mask) switch
  272. {
  273. SamplerType.Texture1D => Dim.Dim1D,
  274. SamplerType.Texture2D => Dim.Dim2D,
  275. SamplerType.Texture3D => Dim.Dim3D,
  276. SamplerType.TextureCube => Dim.Cube,
  277. SamplerType.TextureBuffer => Dim.Buffer,
  278. _ => throw new ArgumentException($"Invalid sampler type \"{type & SamplerType.Mask}\".")
  279. };
  280. }
  281. private static ImageFormat GetImageFormat(TextureFormat format)
  282. {
  283. return format switch
  284. {
  285. TextureFormat.Unknown => ImageFormat.Unknown,
  286. TextureFormat.R8Unorm => ImageFormat.R8,
  287. TextureFormat.R8Snorm => ImageFormat.R8Snorm,
  288. TextureFormat.R8Uint => ImageFormat.R8ui,
  289. TextureFormat.R8Sint => ImageFormat.R8i,
  290. TextureFormat.R16Float => ImageFormat.R16f,
  291. TextureFormat.R16Unorm => ImageFormat.R16,
  292. TextureFormat.R16Snorm => ImageFormat.R16Snorm,
  293. TextureFormat.R16Uint => ImageFormat.R16ui,
  294. TextureFormat.R16Sint => ImageFormat.R16i,
  295. TextureFormat.R32Float => ImageFormat.R32f,
  296. TextureFormat.R32Uint => ImageFormat.R32ui,
  297. TextureFormat.R32Sint => ImageFormat.R32i,
  298. TextureFormat.R8G8Unorm => ImageFormat.Rg8,
  299. TextureFormat.R8G8Snorm => ImageFormat.Rg8Snorm,
  300. TextureFormat.R8G8Uint => ImageFormat.Rg8ui,
  301. TextureFormat.R8G8Sint => ImageFormat.Rg8i,
  302. TextureFormat.R16G16Float => ImageFormat.Rg16f,
  303. TextureFormat.R16G16Unorm => ImageFormat.Rg16,
  304. TextureFormat.R16G16Snorm => ImageFormat.Rg16Snorm,
  305. TextureFormat.R16G16Uint => ImageFormat.Rg16ui,
  306. TextureFormat.R16G16Sint => ImageFormat.Rg16i,
  307. TextureFormat.R32G32Float => ImageFormat.Rg32f,
  308. TextureFormat.R32G32Uint => ImageFormat.Rg32ui,
  309. TextureFormat.R32G32Sint => ImageFormat.Rg32i,
  310. TextureFormat.R8G8B8A8Unorm => ImageFormat.Rgba8,
  311. TextureFormat.R8G8B8A8Snorm => ImageFormat.Rgba8Snorm,
  312. TextureFormat.R8G8B8A8Uint => ImageFormat.Rgba8ui,
  313. TextureFormat.R8G8B8A8Sint => ImageFormat.Rgba8i,
  314. TextureFormat.R16G16B16A16Float => ImageFormat.Rgba16f,
  315. TextureFormat.R16G16B16A16Unorm => ImageFormat.Rgba16,
  316. TextureFormat.R16G16B16A16Snorm => ImageFormat.Rgba16Snorm,
  317. TextureFormat.R16G16B16A16Uint => ImageFormat.Rgba16ui,
  318. TextureFormat.R16G16B16A16Sint => ImageFormat.Rgba16i,
  319. TextureFormat.R32G32B32A32Float => ImageFormat.Rgba32f,
  320. TextureFormat.R32G32B32A32Uint => ImageFormat.Rgba32ui,
  321. TextureFormat.R32G32B32A32Sint => ImageFormat.Rgba32i,
  322. TextureFormat.R10G10B10A2Unorm => ImageFormat.Rgb10A2,
  323. TextureFormat.R10G10B10A2Uint => ImageFormat.Rgb10a2ui,
  324. TextureFormat.R11G11B10Float => ImageFormat.R11fG11fB10f,
  325. _ => throw new ArgumentException($"Invalid texture format \"{format}\".")
  326. };
  327. }
  328. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info, bool perPatch)
  329. {
  330. bool iaIndexing = context.Config.UsedFeatures.HasFlag(FeatureFlags.IaIndexing);
  331. var inputs = perPatch ? info.InputsPerPatch : info.Inputs;
  332. foreach (int attr in inputs)
  333. {
  334. if (!AttributeInfo.Validate(context.Config, attr, isOutAttr: false, perPatch))
  335. {
  336. continue;
  337. }
  338. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  339. if (iaIndexing && isUserAttr && !perPatch)
  340. {
  341. if (context.InputsArray == null)
  342. {
  343. var attrType = context.TypeVector(context.TypeFP32(), (LiteralInteger)4);
  344. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)MaxAttributes));
  345. if (context.Config.Stage == ShaderStage.Geometry)
  346. {
  347. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)context.InputVertices));
  348. }
  349. var spvType = context.TypePointer(StorageClass.Input, attrType);
  350. var spvVar = context.Variable(spvType, StorageClass.Input);
  351. if (context.Config.PassthroughAttributes != 0 && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  352. {
  353. context.Decorate(spvVar, Decoration.PassthroughNV);
  354. }
  355. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)0);
  356. context.AddGlobalVariable(spvVar);
  357. context.InputsArray = spvVar;
  358. }
  359. }
  360. else
  361. {
  362. PixelImap iq = PixelImap.Unused;
  363. if (context.Config.Stage == ShaderStage.Fragment)
  364. {
  365. if (attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd)
  366. {
  367. iq = context.Config.ImapTypes[(attr - AttributeConsts.UserAttributeBase) / 16].GetFirstUsedType();
  368. }
  369. else
  370. {
  371. AttributeInfo attrInfo = AttributeInfo.From(context.Config, attr, isOutAttr: false);
  372. AggregateType elemType = attrInfo.Type & AggregateType.ElementTypeMask;
  373. if (attrInfo.IsBuiltin && (elemType == AggregateType.S32 || elemType == AggregateType.U32))
  374. {
  375. iq = PixelImap.Constant;
  376. }
  377. }
  378. }
  379. DeclareInputOrOutput(context, attr, perPatch, isOutAttr: false, iq);
  380. }
  381. }
  382. }
  383. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info, bool perPatch)
  384. {
  385. bool oaIndexing = context.Config.UsedFeatures.HasFlag(FeatureFlags.OaIndexing);
  386. var outputs = perPatch ? info.OutputsPerPatch : info.Outputs;
  387. foreach (int attr in outputs)
  388. {
  389. if (!AttributeInfo.Validate(context.Config, attr, isOutAttr: true, perPatch))
  390. {
  391. continue;
  392. }
  393. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  394. if (oaIndexing && isUserAttr && !perPatch)
  395. {
  396. if (context.OutputsArray == null)
  397. {
  398. var attrType = context.TypeVector(context.TypeFP32(), (LiteralInteger)4);
  399. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)MaxAttributes));
  400. if (context.Config.Stage == ShaderStage.TessellationControl)
  401. {
  402. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), context.Config.ThreadsPerInputPrimitive));
  403. }
  404. var spvType = context.TypePointer(StorageClass.Output, attrType);
  405. var spvVar = context.Variable(spvType, StorageClass.Output);
  406. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)0);
  407. context.AddGlobalVariable(spvVar);
  408. context.OutputsArray = spvVar;
  409. }
  410. }
  411. else
  412. {
  413. DeclareOutputAttribute(context, attr, perPatch);
  414. }
  415. }
  416. if (context.Config.Stage == ShaderStage.Vertex)
  417. {
  418. DeclareOutputAttribute(context, AttributeConsts.PositionX, perPatch: false);
  419. }
  420. }
  421. private static void DeclareOutputAttribute(CodeGenContext context, int attr, bool perPatch)
  422. {
  423. DeclareInputOrOutput(context, attr, perPatch, isOutAttr: true);
  424. }
  425. public static void DeclareInvocationId(CodeGenContext context)
  426. {
  427. DeclareInputOrOutput(context, AttributeConsts.LaneId, perPatch: false, isOutAttr: false);
  428. }
  429. private static void DeclareInputOrOutput(CodeGenContext context, int attr, bool perPatch, bool isOutAttr, PixelImap iq = PixelImap.Unused)
  430. {
  431. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  432. if (isUserAttr && context.Config.TransformFeedbackEnabled && !perPatch &&
  433. ((isOutAttr && context.Config.LastInVertexPipeline) ||
  434. (!isOutAttr && context.Config.Stage == ShaderStage.Fragment)))
  435. {
  436. DeclareTransformFeedbackInputOrOutput(context, attr, isOutAttr, iq);
  437. return;
  438. }
  439. var dict = perPatch
  440. ? (isOutAttr ? context.OutputsPerPatch : context.InputsPerPatch)
  441. : (isOutAttr ? context.Outputs : context.Inputs);
  442. var attrInfo = perPatch
  443. ? AttributeInfo.FromPatch(context.Config, attr, isOutAttr)
  444. : AttributeInfo.From(context.Config, attr, isOutAttr);
  445. if (dict.ContainsKey(attrInfo.BaseValue))
  446. {
  447. return;
  448. }
  449. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  450. var attrType = context.GetType(attrInfo.Type, attrInfo.Length);
  451. bool builtInPassthrough = false;
  452. if (AttributeInfo.IsArrayAttributeSpirv(context.Config.Stage, isOutAttr) && !perPatch && (!attrInfo.IsBuiltin || AttributeInfo.IsArrayBuiltIn(attr)))
  453. {
  454. int arraySize = context.Config.Stage == ShaderStage.Geometry ? context.InputVertices : 32;
  455. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)arraySize));
  456. if (context.Config.GpPassthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  457. {
  458. builtInPassthrough = true;
  459. }
  460. }
  461. if (context.Config.Stage == ShaderStage.TessellationControl && isOutAttr && !perPatch)
  462. {
  463. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), context.Config.ThreadsPerInputPrimitive));
  464. }
  465. var spvType = context.TypePointer(storageClass, attrType);
  466. var spvVar = context.Variable(spvType, storageClass);
  467. if (builtInPassthrough)
  468. {
  469. context.Decorate(spvVar, Decoration.PassthroughNV);
  470. }
  471. if (attrInfo.IsBuiltin)
  472. {
  473. if (perPatch)
  474. {
  475. context.Decorate(spvVar, Decoration.Patch);
  476. }
  477. context.Decorate(spvVar, Decoration.BuiltIn, (LiteralInteger)GetBuiltIn(context, attrInfo.BaseValue));
  478. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline && isOutAttr)
  479. {
  480. var tfOutput = context.Info.GetTransformFeedbackOutput(attrInfo.BaseValue);
  481. if (tfOutput.Valid)
  482. {
  483. context.Decorate(spvVar, Decoration.XfbBuffer, (LiteralInteger)tfOutput.Buffer);
  484. context.Decorate(spvVar, Decoration.XfbStride, (LiteralInteger)tfOutput.Stride);
  485. context.Decorate(spvVar, Decoration.Offset, (LiteralInteger)tfOutput.Offset);
  486. }
  487. }
  488. }
  489. else if (perPatch)
  490. {
  491. context.Decorate(spvVar, Decoration.Patch);
  492. int location = context.Config.GetPerPatchAttributeLocation((attr - AttributeConsts.UserAttributePerPatchBase) / 16);
  493. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  494. }
  495. else if (isUserAttr)
  496. {
  497. int location = (attr - AttributeConsts.UserAttributeBase) / 16;
  498. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  499. if (!isOutAttr &&
  500. !perPatch &&
  501. (context.Config.PassthroughAttributes & (1 << location)) != 0 &&
  502. context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  503. {
  504. context.Decorate(spvVar, Decoration.PassthroughNV);
  505. }
  506. }
  507. else if (attr >= AttributeConsts.FragmentOutputColorBase && attr < AttributeConsts.FragmentOutputColorEnd)
  508. {
  509. int location = (attr - AttributeConsts.FragmentOutputColorBase) / 16;
  510. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  511. }
  512. if (!isOutAttr)
  513. {
  514. switch (iq)
  515. {
  516. case PixelImap.Constant:
  517. context.Decorate(spvVar, Decoration.Flat);
  518. break;
  519. case PixelImap.ScreenLinear:
  520. context.Decorate(spvVar, Decoration.NoPerspective);
  521. break;
  522. }
  523. }
  524. context.AddGlobalVariable(spvVar);
  525. dict.Add(attrInfo.BaseValue, spvVar);
  526. }
  527. private static void DeclareTransformFeedbackInputOrOutput(CodeGenContext context, int attr, bool isOutAttr, PixelImap iq = PixelImap.Unused)
  528. {
  529. var dict = isOutAttr ? context.Outputs : context.Inputs;
  530. var attrInfo = AttributeInfo.From(context.Config, attr, isOutAttr);
  531. bool hasComponent = true;
  532. int component = (attr >> 2) & 3;
  533. int components = 1;
  534. var type = attrInfo.Type & AggregateType.ElementTypeMask;
  535. if (context.Config.LastInPipeline && isOutAttr)
  536. {
  537. components = context.Info.GetTransformFeedbackOutputComponents(attr);
  538. if (components > 1)
  539. {
  540. attr &= ~0xf;
  541. type = AggregateType.Vector | AggregateType.FP32;
  542. hasComponent = false;
  543. }
  544. }
  545. if (dict.ContainsKey(attr))
  546. {
  547. return;
  548. }
  549. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  550. var attrType = context.GetType(type, components);
  551. if (AttributeInfo.IsArrayAttributeSpirv(context.Config.Stage, isOutAttr) && (!attrInfo.IsBuiltin || AttributeInfo.IsArrayBuiltIn(attr)))
  552. {
  553. int arraySize = context.Config.Stage == ShaderStage.Geometry ? context.InputVertices : 32;
  554. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)arraySize));
  555. }
  556. if (context.Config.Stage == ShaderStage.TessellationControl && isOutAttr)
  557. {
  558. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), context.Config.ThreadsPerInputPrimitive));
  559. }
  560. var spvType = context.TypePointer(storageClass, attrType);
  561. var spvVar = context.Variable(spvType, storageClass);
  562. Debug.Assert(attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd);
  563. int location = (attr - AttributeConsts.UserAttributeBase) / 16;
  564. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  565. if (hasComponent)
  566. {
  567. context.Decorate(spvVar, Decoration.Component, (LiteralInteger)component);
  568. }
  569. if (isOutAttr)
  570. {
  571. var tfOutput = context.Info.GetTransformFeedbackOutput(attr);
  572. if (tfOutput.Valid)
  573. {
  574. context.Decorate(spvVar, Decoration.XfbBuffer, (LiteralInteger)tfOutput.Buffer);
  575. context.Decorate(spvVar, Decoration.XfbStride, (LiteralInteger)tfOutput.Stride);
  576. context.Decorate(spvVar, Decoration.Offset, (LiteralInteger)tfOutput.Offset);
  577. }
  578. }
  579. else
  580. {
  581. if ((context.Config.PassthroughAttributes & (1 << location)) != 0 &&
  582. context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  583. {
  584. context.Decorate(spvVar, Decoration.PassthroughNV);
  585. }
  586. switch (iq)
  587. {
  588. case PixelImap.Constant:
  589. context.Decorate(spvVar, Decoration.Flat);
  590. break;
  591. case PixelImap.ScreenLinear:
  592. context.Decorate(spvVar, Decoration.NoPerspective);
  593. break;
  594. }
  595. }
  596. context.AddGlobalVariable(spvVar);
  597. dict.Add(attr, spvVar);
  598. }
  599. private static BuiltIn GetBuiltIn(CodeGenContext context, int attr)
  600. {
  601. return attr switch
  602. {
  603. AttributeConsts.TessLevelOuter0 => BuiltIn.TessLevelOuter,
  604. AttributeConsts.TessLevelInner0 => BuiltIn.TessLevelInner,
  605. AttributeConsts.Layer => BuiltIn.Layer,
  606. AttributeConsts.ViewportIndex => BuiltIn.ViewportIndex,
  607. AttributeConsts.PointSize => BuiltIn.PointSize,
  608. AttributeConsts.PositionX => context.Config.Stage == ShaderStage.Fragment ? BuiltIn.FragCoord : BuiltIn.Position,
  609. AttributeConsts.ClipDistance0 => BuiltIn.ClipDistance,
  610. AttributeConsts.PointCoordX => BuiltIn.PointCoord,
  611. AttributeConsts.TessCoordX => BuiltIn.TessCoord,
  612. AttributeConsts.InstanceId => BuiltIn.InstanceId,
  613. AttributeConsts.VertexId => BuiltIn.VertexId,
  614. AttributeConsts.BaseInstance => BuiltIn.BaseInstance,
  615. AttributeConsts.BaseVertex => BuiltIn.BaseVertex,
  616. AttributeConsts.InstanceIndex => BuiltIn.InstanceIndex,
  617. AttributeConsts.VertexIndex => BuiltIn.VertexIndex,
  618. AttributeConsts.DrawIndex => BuiltIn.DrawIndex,
  619. AttributeConsts.FrontFacing => BuiltIn.FrontFacing,
  620. AttributeConsts.FragmentOutputDepth => BuiltIn.FragDepth,
  621. AttributeConsts.ThreadKill => BuiltIn.HelperInvocation,
  622. AttributeConsts.ThreadIdX => BuiltIn.LocalInvocationId,
  623. AttributeConsts.CtaIdX => BuiltIn.WorkgroupId,
  624. AttributeConsts.LaneId => BuiltIn.SubgroupLocalInvocationId,
  625. AttributeConsts.InvocationId => BuiltIn.InvocationId,
  626. AttributeConsts.PrimitiveId => BuiltIn.PrimitiveId,
  627. AttributeConsts.PatchVerticesIn => BuiltIn.PatchVertices,
  628. AttributeConsts.EqMask => BuiltIn.SubgroupEqMask,
  629. AttributeConsts.GeMask => BuiltIn.SubgroupGeMask,
  630. AttributeConsts.GtMask => BuiltIn.SubgroupGtMask,
  631. AttributeConsts.LeMask => BuiltIn.SubgroupLeMask,
  632. AttributeConsts.LtMask => BuiltIn.SubgroupLtMask,
  633. AttributeConsts.SupportBlockViewInverseX => BuiltIn.Position,
  634. AttributeConsts.SupportBlockViewInverseY => BuiltIn.Position,
  635. _ => throw new ArgumentException($"Invalid attribute number 0x{attr:X}.")
  636. };
  637. }
  638. private static string GetStagePrefix(ShaderStage stage)
  639. {
  640. return StagePrefixes[(int)stage];
  641. }
  642. }
  643. }