Translator.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  9. namespace Ryujinx.Graphics.Shader.Translation
  10. {
  11. public static class Translator
  12. {
  13. private const int HeaderSize = 0x50;
  14. public static ReadOnlySpan<byte> ExtractCode(ReadOnlySpan<byte> code, bool compute, out int headerSize)
  15. {
  16. headerSize = compute ? 0 : HeaderSize;
  17. Block[] cfg = Decoder.Decode(code, (ulong)headerSize);
  18. if (cfg == null)
  19. {
  20. return code;
  21. }
  22. ulong endAddress = 0;
  23. foreach (Block block in cfg)
  24. {
  25. if (endAddress < block.EndAddress)
  26. {
  27. endAddress = block.EndAddress;
  28. }
  29. }
  30. return code.Slice(0, headerSize + (int)endAddress);
  31. }
  32. public static ShaderProgram Translate(ReadOnlySpan<byte> code, TranslatorCallbacks callbacks, TranslationFlags flags)
  33. {
  34. Operation[] ops = DecodeShader(code, callbacks, flags, out ShaderConfig config, out int size);
  35. return Translate(ops, config, size);
  36. }
  37. public static ShaderProgram Translate(ReadOnlySpan<byte> vpACode, ReadOnlySpan<byte> vpBCode, TranslatorCallbacks callbacks, TranslationFlags flags)
  38. {
  39. Operation[] vpAOps = DecodeShader(vpACode, callbacks, flags, out _, out _);
  40. Operation[] vpBOps = DecodeShader(vpBCode, callbacks, flags, out ShaderConfig config, out int sizeB);
  41. return Translate(Combine(vpAOps, vpBOps), config, sizeB);
  42. }
  43. private static ShaderProgram Translate(Operation[] ops, ShaderConfig config, int size)
  44. {
  45. BasicBlock[] blocks = ControlFlowGraph.MakeCfg(ops);
  46. if (blocks.Length > 0)
  47. {
  48. Dominance.FindDominators(blocks[0], blocks.Length);
  49. Dominance.FindDominanceFrontiers(blocks);
  50. Ssa.Rename(blocks);
  51. Optimizer.RunPass(blocks, config);
  52. Lowering.RunPass(blocks, config);
  53. }
  54. StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(blocks, config);
  55. GlslProgram program = GlslGenerator.Generate(sInfo, config);
  56. ShaderProgramInfo spInfo = new ShaderProgramInfo(
  57. program.CBufferDescriptors,
  58. program.SBufferDescriptors,
  59. program.TextureDescriptors,
  60. program.ImageDescriptors,
  61. sInfo.UsesInstanceId);
  62. string glslCode = program.Code;
  63. return new ShaderProgram(spInfo, config.Stage, glslCode, size);
  64. }
  65. private static Operation[] DecodeShader(
  66. ReadOnlySpan<byte> code,
  67. TranslatorCallbacks callbacks,
  68. TranslationFlags flags,
  69. out ShaderConfig config,
  70. out int size)
  71. {
  72. Block[] cfg;
  73. if ((flags & TranslationFlags.Compute) != 0)
  74. {
  75. config = new ShaderConfig(flags, callbacks);
  76. cfg = Decoder.Decode(code, 0);
  77. }
  78. else
  79. {
  80. config = new ShaderConfig(new ShaderHeader(code), flags, callbacks);
  81. cfg = Decoder.Decode(code, HeaderSize);
  82. }
  83. if (cfg == null)
  84. {
  85. config.PrintLog("Invalid branch detected, failed to build CFG.");
  86. size = 0;
  87. return Array.Empty<Operation>();
  88. }
  89. EmitterContext context = new EmitterContext(config);
  90. ulong maxEndAddress = 0;
  91. for (int blkIndex = 0; blkIndex < cfg.Length; blkIndex++)
  92. {
  93. Block block = cfg[blkIndex];
  94. if (maxEndAddress < block.EndAddress)
  95. {
  96. maxEndAddress = block.EndAddress;
  97. }
  98. context.CurrBlock = block;
  99. context.MarkLabel(context.GetLabel(block.Address));
  100. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  101. {
  102. OpCode op = block.OpCodes[opIndex];
  103. if ((flags & TranslationFlags.DebugMode) != 0)
  104. {
  105. string instName;
  106. if (op.Emitter != null)
  107. {
  108. instName = op.Emitter.Method.Name;
  109. }
  110. else
  111. {
  112. instName = "???";
  113. config.PrintLog($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  114. }
  115. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  116. context.Add(new CommentNode(dbgComment));
  117. }
  118. if (op.NeverExecute)
  119. {
  120. continue;
  121. }
  122. Operand predSkipLbl = null;
  123. bool skipPredicateCheck = op is OpCodeBranch opBranch && !opBranch.PushTarget;
  124. if (op is OpCodeBranchPop opBranchPop)
  125. {
  126. // If the instruction is a SYNC or BRK instruction with only one
  127. // possible target address, then the instruction is basically
  128. // just a simple branch, we can generate code similar to branch
  129. // instructions, with the condition check on the branch itself.
  130. skipPredicateCheck = opBranchPop.Targets.Count < 2;
  131. }
  132. if (!(op.Predicate.IsPT || skipPredicateCheck))
  133. {
  134. Operand label;
  135. if (opIndex == block.OpCodes.Count - 1 && block.Next != null)
  136. {
  137. label = context.GetLabel(block.Next.Address);
  138. }
  139. else
  140. {
  141. label = Label();
  142. predSkipLbl = label;
  143. }
  144. Operand pred = Register(op.Predicate);
  145. if (op.InvertPredicate)
  146. {
  147. context.BranchIfTrue(label, pred);
  148. }
  149. else
  150. {
  151. context.BranchIfFalse(label, pred);
  152. }
  153. }
  154. context.CurrOp = op;
  155. op.Emitter?.Invoke(context);
  156. if (predSkipLbl != null)
  157. {
  158. context.MarkLabel(predSkipLbl);
  159. }
  160. }
  161. }
  162. size = (int)maxEndAddress + (((flags & TranslationFlags.Compute) != 0) ? 0 : HeaderSize);
  163. return context.GetOperations();
  164. }
  165. private static Operation[] Combine(Operation[] a, Operation[] b)
  166. {
  167. // Here we combine two shaders.
  168. // For shader A:
  169. // - All user attribute stores on shader A are turned into copies to a
  170. // temporary variable. It's assumed that shader B will consume them.
  171. // - All return instructions are turned into branch instructions, the
  172. // branch target being the start of the shader B code.
  173. // For shader B:
  174. // - All user attribute loads on shader B are turned into copies from a
  175. // temporary variable, as long that attribute is written by shader A.
  176. List<Operation> output = new List<Operation>(a.Length + b.Length);
  177. Operand[] temps = new Operand[AttributeConsts.UserAttributesCount * 4];
  178. Operand lblB = Label();
  179. for (int index = 0; index < a.Length; index++)
  180. {
  181. Operation operation = a[index];
  182. if (IsUserAttribute(operation.Dest))
  183. {
  184. int tIndex = (operation.Dest.Value - AttributeConsts.UserAttributeBase) / 4;
  185. Operand temp = temps[tIndex];
  186. if (temp == null)
  187. {
  188. temp = Local();
  189. temps[tIndex] = temp;
  190. }
  191. operation.Dest = temp;
  192. }
  193. if (operation.Inst == Instruction.Return)
  194. {
  195. output.Add(new Operation(Instruction.Branch, lblB));
  196. }
  197. else
  198. {
  199. output.Add(operation);
  200. }
  201. }
  202. output.Add(new Operation(Instruction.MarkLabel, lblB));
  203. for (int index = 0; index < b.Length; index++)
  204. {
  205. Operation operation = b[index];
  206. for (int srcIndex = 0; srcIndex < operation.SourcesCount; srcIndex++)
  207. {
  208. Operand src = operation.GetSource(srcIndex);
  209. if (IsUserAttribute(src))
  210. {
  211. Operand temp = temps[(src.Value - AttributeConsts.UserAttributeBase) / 4];
  212. if (temp != null)
  213. {
  214. operation.SetSource(srcIndex, temp);
  215. }
  216. }
  217. }
  218. output.Add(operation);
  219. }
  220. return output.ToArray();
  221. }
  222. private static bool IsUserAttribute(Operand operand)
  223. {
  224. return operand != null &&
  225. operand.Type == OperandType.Attribute &&
  226. operand.Value >= AttributeConsts.UserAttributeBase &&
  227. operand.Value < AttributeConsts.UserAttributeEnd;
  228. }
  229. }
  230. }