SpirvGenerator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  3. using Ryujinx.Graphics.Shader.StructuredIr;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using System.Collections.Generic;
  7. using static Spv.Specification;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
  9. {
  10. using SpvInstruction = Spv.Generator.Instruction;
  11. using SpvLiteralInteger = Spv.Generator.LiteralInteger;
  12. using SpvInstructionPool = Spv.Generator.GeneratorPool<Spv.Generator.Instruction>;
  13. using SpvLiteralIntegerPool = Spv.Generator.GeneratorPool<Spv.Generator.LiteralInteger>;
  14. static class SpirvGenerator
  15. {
  16. // Resource pools for Spirv generation. Note: Increase count when more threads are being used.
  17. private const int GeneratorPoolCount = 1;
  18. private static ObjectPool<SpvInstructionPool> InstructionPool;
  19. private static ObjectPool<SpvLiteralIntegerPool> IntegerPool;
  20. private static object PoolLock;
  21. static SpirvGenerator()
  22. {
  23. InstructionPool = new (() => new SpvInstructionPool(), GeneratorPoolCount);
  24. IntegerPool = new (() => new SpvLiteralIntegerPool(), GeneratorPoolCount);
  25. PoolLock = new object();
  26. }
  27. private const HelperFunctionsMask NeedsInvocationIdMask =
  28. HelperFunctionsMask.Shuffle |
  29. HelperFunctionsMask.ShuffleDown |
  30. HelperFunctionsMask.ShuffleUp |
  31. HelperFunctionsMask.ShuffleXor |
  32. HelperFunctionsMask.SwizzleAdd;
  33. public static byte[] Generate(StructuredProgramInfo info, ShaderConfig config)
  34. {
  35. SpvInstructionPool instPool;
  36. SpvLiteralIntegerPool integerPool;
  37. lock (PoolLock)
  38. {
  39. instPool = InstructionPool.Allocate();
  40. integerPool = IntegerPool.Allocate();
  41. }
  42. CodeGenContext context = new CodeGenContext(info, config, instPool, integerPool);
  43. context.AddCapability(Capability.GroupNonUniformBallot);
  44. context.AddCapability(Capability.ImageBuffer);
  45. context.AddCapability(Capability.ImageGatherExtended);
  46. context.AddCapability(Capability.ImageQuery);
  47. context.AddCapability(Capability.SampledBuffer);
  48. context.AddCapability(Capability.SubgroupBallotKHR);
  49. context.AddCapability(Capability.SubgroupVoteKHR);
  50. if (config.TransformFeedbackEnabled && config.LastInVertexPipeline)
  51. {
  52. context.AddCapability(Capability.TransformFeedback);
  53. }
  54. if (config.Stage == ShaderStage.Fragment && context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  55. {
  56. context.AddCapability(Capability.FragmentShaderPixelInterlockEXT);
  57. context.AddExtension("SPV_EXT_fragment_shader_interlock");
  58. }
  59. else if (config.Stage == ShaderStage.Geometry)
  60. {
  61. context.AddCapability(Capability.Geometry);
  62. if (config.GpPassthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  63. {
  64. context.AddExtension("SPV_NV_geometry_shader_passthrough");
  65. context.AddCapability(Capability.GeometryShaderPassthroughNV);
  66. }
  67. }
  68. else if (config.Stage == ShaderStage.TessellationControl || config.Stage == ShaderStage.TessellationEvaluation)
  69. {
  70. context.AddCapability(Capability.Tessellation);
  71. }
  72. context.AddExtension("SPV_KHR_shader_ballot");
  73. context.AddExtension("SPV_KHR_subgroup_vote");
  74. Declarations.DeclareAll(context, info);
  75. if ((info.HelperFunctionsMask & NeedsInvocationIdMask) != 0)
  76. {
  77. Declarations.DeclareInvocationId(context);
  78. }
  79. for (int funcIndex = 0; funcIndex < info.Functions.Count; funcIndex++)
  80. {
  81. var function = info.Functions[funcIndex];
  82. var retType = context.GetType(function.ReturnType.Convert());
  83. var funcArgs = new SpvInstruction[function.InArguments.Length + function.OutArguments.Length];
  84. for (int argIndex = 0; argIndex < funcArgs.Length; argIndex++)
  85. {
  86. var argType = context.GetType(function.GetArgumentType(argIndex).Convert());
  87. var argPointerType = context.TypePointer(StorageClass.Function, argType);
  88. funcArgs[argIndex] = argPointerType;
  89. }
  90. var funcType = context.TypeFunction(retType, false, funcArgs);
  91. var spvFunc = context.Function(retType, FunctionControlMask.MaskNone, funcType);
  92. context.DeclareFunction(funcIndex, function, spvFunc);
  93. }
  94. for (int funcIndex = 0; funcIndex < info.Functions.Count; funcIndex++)
  95. {
  96. Generate(context, info, funcIndex);
  97. }
  98. byte[] result = context.Generate();
  99. lock (PoolLock)
  100. {
  101. InstructionPool.Release(instPool);
  102. IntegerPool.Release(integerPool);
  103. }
  104. return result;
  105. }
  106. private static void Generate(CodeGenContext context, StructuredProgramInfo info, int funcIndex)
  107. {
  108. var function = info.Functions[funcIndex];
  109. (_, var spvFunc) = context.GetFunction(funcIndex);
  110. context.AddFunction(spvFunc);
  111. context.StartFunction();
  112. Declarations.DeclareParameters(context, function);
  113. context.EnterBlock(function.MainBlock);
  114. Declarations.DeclareLocals(context, function);
  115. Declarations.DeclareLocalForArgs(context, info.Functions);
  116. Generate(context, function.MainBlock);
  117. // Functions must always end with a return.
  118. if (!(function.MainBlock.Last is AstOperation operation) ||
  119. (operation.Inst != Instruction.Return && operation.Inst != Instruction.Discard))
  120. {
  121. context.Return();
  122. }
  123. context.FunctionEnd();
  124. if (funcIndex == 0)
  125. {
  126. context.AddEntryPoint(context.Config.Stage.Convert(), spvFunc, "main", context.GetMainInterface());
  127. if (context.Config.Stage == ShaderStage.TessellationControl)
  128. {
  129. context.AddExecutionMode(spvFunc, ExecutionMode.OutputVertices, (SpvLiteralInteger)context.Config.ThreadsPerInputPrimitive);
  130. }
  131. else if (context.Config.Stage == ShaderStage.TessellationEvaluation)
  132. {
  133. switch (context.Config.GpuAccessor.QueryTessPatchType())
  134. {
  135. case TessPatchType.Isolines:
  136. context.AddExecutionMode(spvFunc, ExecutionMode.Isolines);
  137. break;
  138. case TessPatchType.Triangles:
  139. context.AddExecutionMode(spvFunc, ExecutionMode.Triangles);
  140. break;
  141. case TessPatchType.Quads:
  142. context.AddExecutionMode(spvFunc, ExecutionMode.Quads);
  143. break;
  144. }
  145. switch (context.Config.GpuAccessor.QueryTessSpacing())
  146. {
  147. case TessSpacing.EqualSpacing:
  148. context.AddExecutionMode(spvFunc, ExecutionMode.SpacingEqual);
  149. break;
  150. case TessSpacing.FractionalEventSpacing:
  151. context.AddExecutionMode(spvFunc, ExecutionMode.SpacingFractionalEven);
  152. break;
  153. case TessSpacing.FractionalOddSpacing:
  154. context.AddExecutionMode(spvFunc, ExecutionMode.SpacingFractionalOdd);
  155. break;
  156. }
  157. if (context.Config.GpuAccessor.QueryTessCw())
  158. {
  159. context.AddExecutionMode(spvFunc, ExecutionMode.VertexOrderCw);
  160. }
  161. else
  162. {
  163. context.AddExecutionMode(spvFunc, ExecutionMode.VertexOrderCcw);
  164. }
  165. }
  166. else if (context.Config.Stage == ShaderStage.Geometry)
  167. {
  168. InputTopology inputTopology = context.Config.GpuAccessor.QueryPrimitiveTopology();
  169. context.AddExecutionMode(spvFunc, inputTopology switch
  170. {
  171. InputTopology.Points => ExecutionMode.InputPoints,
  172. InputTopology.Lines => ExecutionMode.InputLines,
  173. InputTopology.LinesAdjacency => ExecutionMode.InputLinesAdjacency,
  174. InputTopology.Triangles => ExecutionMode.Triangles,
  175. InputTopology.TrianglesAdjacency => ExecutionMode.InputTrianglesAdjacency,
  176. _ => throw new InvalidOperationException($"Invalid input topology \"{inputTopology}\".")
  177. });
  178. context.AddExecutionMode(spvFunc, ExecutionMode.Invocations, (SpvLiteralInteger)context.Config.ThreadsPerInputPrimitive);
  179. context.AddExecutionMode(spvFunc, context.Config.OutputTopology switch
  180. {
  181. OutputTopology.PointList => ExecutionMode.OutputPoints,
  182. OutputTopology.LineStrip => ExecutionMode.OutputLineStrip,
  183. OutputTopology.TriangleStrip => ExecutionMode.OutputTriangleStrip,
  184. _ => throw new InvalidOperationException($"Invalid output topology \"{context.Config.OutputTopology}\".")
  185. });
  186. int maxOutputVertices = context.Config.GpPassthrough ? context.InputVertices : context.Config.MaxOutputVertices;
  187. context.AddExecutionMode(spvFunc, ExecutionMode.OutputVertices, (SpvLiteralInteger)maxOutputVertices);
  188. }
  189. else if (context.Config.Stage == ShaderStage.Fragment)
  190. {
  191. context.AddExecutionMode(spvFunc, context.Config.Options.TargetApi == TargetApi.Vulkan
  192. ? ExecutionMode.OriginUpperLeft
  193. : ExecutionMode.OriginLowerLeft);
  194. if (context.Outputs.ContainsKey(AttributeConsts.FragmentOutputDepth))
  195. {
  196. context.AddExecutionMode(spvFunc, ExecutionMode.DepthReplacing);
  197. }
  198. if (context.Config.GpuAccessor.QueryEarlyZForce())
  199. {
  200. context.AddExecutionMode(spvFunc, ExecutionMode.EarlyFragmentTests);
  201. }
  202. if ((info.HelperFunctionsMask & HelperFunctionsMask.FSI) != 0 &&
  203. context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  204. {
  205. context.AddExecutionMode(spvFunc, ExecutionMode.PixelInterlockOrderedEXT);
  206. }
  207. }
  208. else if (context.Config.Stage == ShaderStage.Compute)
  209. {
  210. var localSizeX = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeX();
  211. var localSizeY = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeY();
  212. var localSizeZ = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeZ();
  213. context.AddExecutionMode(
  214. spvFunc,
  215. ExecutionMode.LocalSize,
  216. localSizeX,
  217. localSizeY,
  218. localSizeZ);
  219. }
  220. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline)
  221. {
  222. context.AddExecutionMode(spvFunc, ExecutionMode.Xfb);
  223. }
  224. }
  225. }
  226. private static void Generate(CodeGenContext context, AstBlock block)
  227. {
  228. AstBlockVisitor visitor = new AstBlockVisitor(block);
  229. var loopTargets = new Dictionary<AstBlock, (SpvInstruction, SpvInstruction)>();
  230. context.LoopTargets = loopTargets;
  231. visitor.BlockEntered += (sender, e) =>
  232. {
  233. AstBlock mergeBlock = e.Block.Parent;
  234. if (e.Block.Type == AstBlockType.If)
  235. {
  236. AstBlock ifTrueBlock = e.Block;
  237. AstBlock ifFalseBlock;
  238. if (AstHelper.Next(e.Block) is AstBlock nextBlock && nextBlock.Type == AstBlockType.Else)
  239. {
  240. ifFalseBlock = nextBlock;
  241. }
  242. else
  243. {
  244. ifFalseBlock = mergeBlock;
  245. }
  246. var condition = context.Get(AggregateType.Bool, e.Block.Condition);
  247. context.SelectionMerge(context.GetNextLabel(mergeBlock), SelectionControlMask.MaskNone);
  248. context.BranchConditional(condition, context.GetNextLabel(ifTrueBlock), context.GetNextLabel(ifFalseBlock));
  249. }
  250. else if (e.Block.Type == AstBlockType.DoWhile)
  251. {
  252. var continueTarget = context.Label();
  253. loopTargets.Add(e.Block, (context.NewBlock(), continueTarget));
  254. context.LoopMerge(context.GetNextLabel(mergeBlock), continueTarget, LoopControlMask.MaskNone);
  255. context.Branch(context.GetFirstLabel(e.Block));
  256. }
  257. context.EnterBlock(e.Block);
  258. };
  259. visitor.BlockLeft += (sender, e) =>
  260. {
  261. if (e.Block.Parent != null)
  262. {
  263. if (e.Block.Type == AstBlockType.DoWhile)
  264. {
  265. // This is a loop, we need to jump back to the loop header
  266. // if the condition is true.
  267. AstBlock mergeBlock = e.Block.Parent;
  268. (var loopTarget, var continueTarget) = loopTargets[e.Block];
  269. context.Branch(continueTarget);
  270. context.AddLabel(continueTarget);
  271. var condition = context.Get(AggregateType.Bool, e.Block.Condition);
  272. context.BranchConditional(condition, loopTarget, context.GetNextLabel(mergeBlock));
  273. }
  274. else
  275. {
  276. // We only need a branch if the last instruction didn't
  277. // already cause the program to exit or jump elsewhere.
  278. bool lastIsCf = e.Block.Last is AstOperation lastOp &&
  279. (lastOp.Inst == Instruction.Discard ||
  280. lastOp.Inst == Instruction.LoopBreak ||
  281. lastOp.Inst == Instruction.LoopContinue ||
  282. lastOp.Inst == Instruction.Return);
  283. if (!lastIsCf)
  284. {
  285. context.Branch(context.GetNextLabel(e.Block.Parent));
  286. }
  287. }
  288. bool hasElse = AstHelper.Next(e.Block) is AstBlock nextBlock &&
  289. (nextBlock.Type == AstBlockType.Else ||
  290. nextBlock.Type == AstBlockType.ElseIf);
  291. // Re-enter the parent block.
  292. if (e.Block.Parent != null && !hasElse)
  293. {
  294. context.EnterBlock(e.Block.Parent);
  295. }
  296. }
  297. };
  298. foreach (IAstNode node in visitor.Visit())
  299. {
  300. if (node is AstAssignment assignment)
  301. {
  302. var dest = (AstOperand)assignment.Destination;
  303. if (dest.Type == OperandType.LocalVariable)
  304. {
  305. var source = context.Get(dest.VarType.Convert(), assignment.Source);
  306. context.Store(context.GetLocalPointer(dest), source);
  307. }
  308. else if (dest.Type == OperandType.Attribute || dest.Type == OperandType.AttributePerPatch)
  309. {
  310. if (AttributeInfo.Validate(context.Config, dest.Value, isOutAttr: true))
  311. {
  312. bool perPatch = dest.Type == OperandType.AttributePerPatch;
  313. AggregateType elemType;
  314. var elemPointer = perPatch
  315. ? context.GetAttributePerPatchElemPointer(dest.Value, true, out elemType)
  316. : context.GetAttributeElemPointer(dest.Value, true, null, out elemType);
  317. context.Store(elemPointer, context.Get(elemType, assignment.Source));
  318. }
  319. }
  320. else if (dest.Type == OperandType.Argument)
  321. {
  322. var source = context.Get(dest.VarType.Convert(), assignment.Source);
  323. context.Store(context.GetArgumentPointer(dest), source);
  324. }
  325. else
  326. {
  327. throw new NotImplementedException(dest.Type.ToString());
  328. }
  329. }
  330. else if (node is AstOperation operation)
  331. {
  332. Instructions.Generate(context, operation);
  333. }
  334. }
  335. }
  336. }
  337. }