SpirvGenerator.cs 18 KB

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