SpirvGenerator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. bool tessCw = context.Config.GpuAccessor.QueryTessCw();
  158. if (context.Config.Options.TargetApi == TargetApi.Vulkan)
  159. {
  160. // We invert the front face on Vulkan backend, so we need to do that here aswell.
  161. tessCw = !tessCw;
  162. }
  163. if (tessCw)
  164. {
  165. context.AddExecutionMode(spvFunc, ExecutionMode.VertexOrderCw);
  166. }
  167. else
  168. {
  169. context.AddExecutionMode(spvFunc, ExecutionMode.VertexOrderCcw);
  170. }
  171. }
  172. else if (context.Config.Stage == ShaderStage.Geometry)
  173. {
  174. InputTopology inputTopology = context.Config.GpuAccessor.QueryPrimitiveTopology();
  175. context.AddExecutionMode(spvFunc, inputTopology switch
  176. {
  177. InputTopology.Points => ExecutionMode.InputPoints,
  178. InputTopology.Lines => ExecutionMode.InputLines,
  179. InputTopology.LinesAdjacency => ExecutionMode.InputLinesAdjacency,
  180. InputTopology.Triangles => ExecutionMode.Triangles,
  181. InputTopology.TrianglesAdjacency => ExecutionMode.InputTrianglesAdjacency,
  182. _ => throw new InvalidOperationException($"Invalid input topology \"{inputTopology}\".")
  183. });
  184. context.AddExecutionMode(spvFunc, ExecutionMode.Invocations, (SpvLiteralInteger)context.Config.ThreadsPerInputPrimitive);
  185. context.AddExecutionMode(spvFunc, context.Config.OutputTopology switch
  186. {
  187. OutputTopology.PointList => ExecutionMode.OutputPoints,
  188. OutputTopology.LineStrip => ExecutionMode.OutputLineStrip,
  189. OutputTopology.TriangleStrip => ExecutionMode.OutputTriangleStrip,
  190. _ => throw new InvalidOperationException($"Invalid output topology \"{context.Config.OutputTopology}\".")
  191. });
  192. int maxOutputVertices = context.Config.GpPassthrough ? context.InputVertices : context.Config.MaxOutputVertices;
  193. context.AddExecutionMode(spvFunc, ExecutionMode.OutputVertices, (SpvLiteralInteger)maxOutputVertices);
  194. }
  195. else if (context.Config.Stage == ShaderStage.Fragment)
  196. {
  197. context.AddExecutionMode(spvFunc, context.Config.Options.TargetApi == TargetApi.Vulkan
  198. ? ExecutionMode.OriginUpperLeft
  199. : ExecutionMode.OriginLowerLeft);
  200. if (context.Outputs.ContainsKey(AttributeConsts.FragmentOutputDepth))
  201. {
  202. context.AddExecutionMode(spvFunc, ExecutionMode.DepthReplacing);
  203. }
  204. if (context.Config.GpuAccessor.QueryEarlyZForce())
  205. {
  206. context.AddExecutionMode(spvFunc, ExecutionMode.EarlyFragmentTests);
  207. }
  208. if ((info.HelperFunctionsMask & HelperFunctionsMask.FSI) != 0 &&
  209. context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  210. {
  211. context.AddExecutionMode(spvFunc, ExecutionMode.PixelInterlockOrderedEXT);
  212. }
  213. }
  214. else if (context.Config.Stage == ShaderStage.Compute)
  215. {
  216. var localSizeX = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeX();
  217. var localSizeY = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeY();
  218. var localSizeZ = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeZ();
  219. context.AddExecutionMode(
  220. spvFunc,
  221. ExecutionMode.LocalSize,
  222. localSizeX,
  223. localSizeY,
  224. localSizeZ);
  225. }
  226. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline)
  227. {
  228. context.AddExecutionMode(spvFunc, ExecutionMode.Xfb);
  229. }
  230. }
  231. }
  232. private static void Generate(CodeGenContext context, AstBlock block)
  233. {
  234. AstBlockVisitor visitor = new AstBlockVisitor(block);
  235. var loopTargets = new Dictionary<AstBlock, (SpvInstruction, SpvInstruction)>();
  236. context.LoopTargets = loopTargets;
  237. visitor.BlockEntered += (sender, e) =>
  238. {
  239. AstBlock mergeBlock = e.Block.Parent;
  240. if (e.Block.Type == AstBlockType.If)
  241. {
  242. AstBlock ifTrueBlock = e.Block;
  243. AstBlock ifFalseBlock;
  244. if (AstHelper.Next(e.Block) is AstBlock nextBlock && nextBlock.Type == AstBlockType.Else)
  245. {
  246. ifFalseBlock = nextBlock;
  247. }
  248. else
  249. {
  250. ifFalseBlock = mergeBlock;
  251. }
  252. var condition = context.Get(AggregateType.Bool, e.Block.Condition);
  253. context.SelectionMerge(context.GetNextLabel(mergeBlock), SelectionControlMask.MaskNone);
  254. context.BranchConditional(condition, context.GetNextLabel(ifTrueBlock), context.GetNextLabel(ifFalseBlock));
  255. }
  256. else if (e.Block.Type == AstBlockType.DoWhile)
  257. {
  258. var continueTarget = context.Label();
  259. loopTargets.Add(e.Block, (context.NewBlock(), continueTarget));
  260. context.LoopMerge(context.GetNextLabel(mergeBlock), continueTarget, LoopControlMask.MaskNone);
  261. context.Branch(context.GetFirstLabel(e.Block));
  262. }
  263. context.EnterBlock(e.Block);
  264. };
  265. visitor.BlockLeft += (sender, e) =>
  266. {
  267. if (e.Block.Parent != null)
  268. {
  269. if (e.Block.Type == AstBlockType.DoWhile)
  270. {
  271. // This is a loop, we need to jump back to the loop header
  272. // if the condition is true.
  273. AstBlock mergeBlock = e.Block.Parent;
  274. (var loopTarget, var continueTarget) = loopTargets[e.Block];
  275. context.Branch(continueTarget);
  276. context.AddLabel(continueTarget);
  277. var condition = context.Get(AggregateType.Bool, e.Block.Condition);
  278. context.BranchConditional(condition, loopTarget, context.GetNextLabel(mergeBlock));
  279. }
  280. else
  281. {
  282. // We only need a branch if the last instruction didn't
  283. // already cause the program to exit or jump elsewhere.
  284. bool lastIsCf = e.Block.Last is AstOperation lastOp &&
  285. (lastOp.Inst == Instruction.Discard ||
  286. lastOp.Inst == Instruction.LoopBreak ||
  287. lastOp.Inst == Instruction.LoopContinue ||
  288. lastOp.Inst == Instruction.Return);
  289. if (!lastIsCf)
  290. {
  291. context.Branch(context.GetNextLabel(e.Block.Parent));
  292. }
  293. }
  294. bool hasElse = AstHelper.Next(e.Block) is AstBlock nextBlock &&
  295. (nextBlock.Type == AstBlockType.Else ||
  296. nextBlock.Type == AstBlockType.ElseIf);
  297. // Re-enter the parent block.
  298. if (e.Block.Parent != null && !hasElse)
  299. {
  300. context.EnterBlock(e.Block.Parent);
  301. }
  302. }
  303. };
  304. foreach (IAstNode node in visitor.Visit())
  305. {
  306. if (node is AstAssignment assignment)
  307. {
  308. var dest = (AstOperand)assignment.Destination;
  309. if (dest.Type == OperandType.LocalVariable)
  310. {
  311. var source = context.Get(dest.VarType.Convert(), assignment.Source);
  312. context.Store(context.GetLocalPointer(dest), source);
  313. }
  314. else if (dest.Type == OperandType.Attribute || dest.Type == OperandType.AttributePerPatch)
  315. {
  316. bool perPatch = dest.Type == OperandType.AttributePerPatch;
  317. if (AttributeInfo.Validate(context.Config, dest.Value, isOutAttr: true, perPatch))
  318. {
  319. AggregateType elemType;
  320. var elemPointer = perPatch
  321. ? context.GetAttributePerPatchElemPointer(dest.Value, true, out elemType)
  322. : context.GetAttributeElemPointer(dest.Value, true, null, out elemType);
  323. context.Store(elemPointer, context.Get(elemType, assignment.Source));
  324. }
  325. }
  326. else if (dest.Type == OperandType.Argument)
  327. {
  328. var source = context.Get(dest.VarType.Convert(), assignment.Source);
  329. context.Store(context.GetArgumentPointer(dest), source);
  330. }
  331. else
  332. {
  333. throw new NotImplementedException(dest.Type.ToString());
  334. }
  335. }
  336. else if (node is AstOperation operation)
  337. {
  338. Instructions.Generate(context, operation);
  339. }
  340. }
  341. }
  342. }
  343. }