Translator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using Ryujinx.Graphics.Shader.CodeGen.Glsl;
  2. using Ryujinx.Graphics.Shader.Decoders;
  3. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  4. using Ryujinx.Graphics.Shader.StructuredIr;
  5. using Ryujinx.Graphics.Shader.Translation.Optimizations;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Numerics;
  9. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  10. namespace Ryujinx.Graphics.Shader.Translation
  11. {
  12. public static class Translator
  13. {
  14. private const int HeaderSize = 0x50;
  15. internal struct FunctionCode
  16. {
  17. public Operation[] Code { get; }
  18. public FunctionCode(Operation[] code)
  19. {
  20. Code = code;
  21. }
  22. }
  23. public static TranslatorContext CreateContext(
  24. ulong address,
  25. IGpuAccessor gpuAccessor,
  26. TranslationOptions options,
  27. TranslationCounts counts = null)
  28. {
  29. counts ??= new TranslationCounts();
  30. Block[][] cfg = DecodeShader(address, gpuAccessor, options, counts, out ShaderConfig config);
  31. return new TranslatorContext(address, cfg, config);
  32. }
  33. internal static ShaderProgram Translate(FunctionCode[] functions, ShaderConfig config, out ShaderProgramInfo shaderProgramInfo)
  34. {
  35. var cfgs = new ControlFlowGraph[functions.Length];
  36. var frus = new RegisterUsage.FunctionRegisterUsage[functions.Length];
  37. for (int i = 0; i < functions.Length; i++)
  38. {
  39. cfgs[i] = ControlFlowGraph.Create(functions[i].Code);
  40. if (i != 0)
  41. {
  42. frus[i] = RegisterUsage.RunPass(cfgs[i]);
  43. }
  44. }
  45. Function[] funcs = new Function[functions.Length];
  46. for (int i = 0; i < functions.Length; i++)
  47. {
  48. var cfg = cfgs[i];
  49. int inArgumentsCount = 0;
  50. int outArgumentsCount = 0;
  51. if (i != 0)
  52. {
  53. var fru = frus[i];
  54. inArgumentsCount = fru.InArguments.Length;
  55. outArgumentsCount = fru.OutArguments.Length;
  56. }
  57. if (cfg.Blocks.Length != 0)
  58. {
  59. RegisterUsage.FixupCalls(cfg.Blocks, frus);
  60. Dominance.FindDominators(cfg);
  61. Dominance.FindDominanceFrontiers(cfg.Blocks);
  62. Ssa.Rename(cfg.Blocks);
  63. Optimizer.RunPass(cfg.Blocks, config);
  64. Rewriter.RunPass(cfg.Blocks, config);
  65. }
  66. funcs[i] = new Function(cfg.Blocks, $"fun{i}", false, inArgumentsCount, outArgumentsCount);
  67. }
  68. StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(funcs, config);
  69. ShaderProgram program;
  70. switch (config.Options.TargetLanguage)
  71. {
  72. case TargetLanguage.Glsl:
  73. program = new ShaderProgram(config.Stage, GlslGenerator.Generate(sInfo, config));
  74. break;
  75. default:
  76. throw new NotImplementedException(config.Options.TargetLanguage.ToString());
  77. }
  78. shaderProgramInfo = new ShaderProgramInfo(
  79. config.GetConstantBufferDescriptors(),
  80. config.GetStorageBufferDescriptors(),
  81. config.GetTextureDescriptors(),
  82. config.GetImageDescriptors(),
  83. config.UsedFeatures.HasFlag(FeatureFlags.InstanceId),
  84. config.ClipDistancesWritten);
  85. return program;
  86. }
  87. private static Block[][] DecodeShader(
  88. ulong address,
  89. IGpuAccessor gpuAccessor,
  90. TranslationOptions options,
  91. TranslationCounts counts,
  92. out ShaderConfig config)
  93. {
  94. Block[][] cfg;
  95. ulong maxEndAddress = 0;
  96. if ((options.Flags & TranslationFlags.Compute) != 0)
  97. {
  98. config = new ShaderConfig(gpuAccessor, options, counts);
  99. cfg = Decoder.Decode(config, address);
  100. }
  101. else
  102. {
  103. config = new ShaderConfig(new ShaderHeader(gpuAccessor, address), gpuAccessor, options, counts);
  104. cfg = Decoder.Decode(config, address + HeaderSize);
  105. }
  106. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  107. {
  108. for (int blkIndex = 0; blkIndex < cfg[funcIndex].Length; blkIndex++)
  109. {
  110. Block block = cfg[funcIndex][blkIndex];
  111. if (maxEndAddress < block.EndAddress)
  112. {
  113. maxEndAddress = block.EndAddress;
  114. }
  115. if (!config.UsedFeatures.HasFlag(FeatureFlags.Bindless))
  116. {
  117. for (int index = 0; index < block.OpCodes.Count; index++)
  118. {
  119. if (block.OpCodes[index] is OpCodeTextureBase texture)
  120. {
  121. config.TextureHandlesForCache.Add(texture.HandleOffset);
  122. }
  123. }
  124. }
  125. }
  126. }
  127. config.SizeAdd((int)maxEndAddress + (options.Flags.HasFlag(TranslationFlags.Compute) ? 0 : HeaderSize));
  128. return cfg;
  129. }
  130. internal static FunctionCode[] EmitShader(Block[][] cfg, ShaderConfig config, bool initializeOutputs, out int initializationOperations)
  131. {
  132. initializationOperations = 0;
  133. Dictionary<ulong, int> funcIds = new Dictionary<ulong, int>();
  134. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  135. {
  136. funcIds.Add(cfg[funcIndex][0].Address, funcIndex);
  137. }
  138. List<FunctionCode> funcs = new List<FunctionCode>();
  139. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  140. {
  141. EmitterContext context = new EmitterContext(config, funcIndex != 0, funcIds);
  142. if (initializeOutputs && funcIndex == 0)
  143. {
  144. EmitOutputsInitialization(context, config);
  145. initializationOperations = context.OperationsCount;
  146. }
  147. for (int blkIndex = 0; blkIndex < cfg[funcIndex].Length; blkIndex++)
  148. {
  149. Block block = cfg[funcIndex][blkIndex];
  150. context.CurrBlock = block;
  151. context.MarkLabel(context.GetLabel(block.Address));
  152. EmitOps(context, block);
  153. }
  154. funcs.Add(new FunctionCode(context.GetOperations()));
  155. }
  156. return funcs.ToArray();
  157. }
  158. private static void EmitOutputsInitialization(EmitterContext context, ShaderConfig config)
  159. {
  160. // Compute has no output attributes, and fragment is the last stage, so we
  161. // don't need to initialize outputs on those stages.
  162. if (config.Stage == ShaderStage.Compute || config.Stage == ShaderStage.Fragment)
  163. {
  164. return;
  165. }
  166. void InitializeOutput(int baseAttr)
  167. {
  168. for (int c = 0; c < 4; c++)
  169. {
  170. context.Copy(Attribute(baseAttr + c * 4), ConstF(c == 3 ? 1f : 0f));
  171. }
  172. }
  173. if (config.Stage == ShaderStage.Vertex)
  174. {
  175. InitializeOutput(AttributeConsts.PositionX);
  176. }
  177. int usedAttribtes = context.Config.UsedOutputAttributes;
  178. while (usedAttribtes != 0)
  179. {
  180. int index = BitOperations.TrailingZeroCount(usedAttribtes);
  181. InitializeOutput(AttributeConsts.UserAttributeBase + index * 16);
  182. usedAttribtes &= ~(1 << index);
  183. }
  184. }
  185. private static void EmitOps(EmitterContext context, Block block)
  186. {
  187. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  188. {
  189. OpCode op = block.OpCodes[opIndex];
  190. if ((context.Config.Options.Flags & TranslationFlags.DebugMode) != 0)
  191. {
  192. string instName;
  193. if (op.Emitter != null)
  194. {
  195. instName = op.Emitter.Method.Name;
  196. }
  197. else
  198. {
  199. instName = "???";
  200. context.Config.GpuAccessor.Log($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  201. }
  202. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  203. context.Add(new CommentNode(dbgComment));
  204. }
  205. if (op.NeverExecute)
  206. {
  207. continue;
  208. }
  209. Operand predSkipLbl = null;
  210. bool skipPredicateCheck = op is OpCodeBranch opBranch && !opBranch.PushTarget;
  211. if (op is OpCodeBranchPop opBranchPop)
  212. {
  213. // If the instruction is a SYNC or BRK instruction with only one
  214. // possible target address, then the instruction is basically
  215. // just a simple branch, we can generate code similar to branch
  216. // instructions, with the condition check on the branch itself.
  217. skipPredicateCheck = opBranchPop.Targets.Count < 2;
  218. }
  219. if (!(op.Predicate.IsPT || skipPredicateCheck))
  220. {
  221. Operand label;
  222. if (opIndex == block.OpCodes.Count - 1 && block.Next != null)
  223. {
  224. label = context.GetLabel(block.Next.Address);
  225. }
  226. else
  227. {
  228. label = Label();
  229. predSkipLbl = label;
  230. }
  231. Operand pred = Register(op.Predicate);
  232. if (op.InvertPredicate)
  233. {
  234. context.BranchIfTrue(label, pred);
  235. }
  236. else
  237. {
  238. context.BranchIfFalse(label, pred);
  239. }
  240. }
  241. context.CurrOp = op;
  242. op.Emitter?.Invoke(context);
  243. if (predSkipLbl != null)
  244. {
  245. context.MarkLabel(predSkipLbl);
  246. }
  247. }
  248. }
  249. }
  250. }