SpirvGenerator.cs 18 KB

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