Translator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. using Ryujinx.Graphics.Shader.CodeGen.Glsl;
  2. using Ryujinx.Graphics.Shader.CodeGen.Spirv;
  3. using Ryujinx.Graphics.Shader.Decoders;
  4. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  5. using Ryujinx.Graphics.Shader.StructuredIr;
  6. using Ryujinx.Graphics.Shader.Translation.Optimizations;
  7. using System;
  8. using System.Linq;
  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(ulong address, IGpuAccessor gpuAccessor, TranslationOptions options)
  24. {
  25. return DecodeShader(address, gpuAccessor, options);
  26. }
  27. internal static ShaderProgram Translate(FunctionCode[] functions, ShaderConfig config)
  28. {
  29. var cfgs = new ControlFlowGraph[functions.Length];
  30. var frus = new RegisterUsage.FunctionRegisterUsage[functions.Length];
  31. for (int i = 0; i < functions.Length; i++)
  32. {
  33. cfgs[i] = ControlFlowGraph.Create(functions[i].Code);
  34. if (i != 0)
  35. {
  36. frus[i] = RegisterUsage.RunPass(cfgs[i]);
  37. }
  38. }
  39. Function[] funcs = new Function[functions.Length];
  40. for (int i = 0; i < functions.Length; i++)
  41. {
  42. var cfg = cfgs[i];
  43. int inArgumentsCount = 0;
  44. int outArgumentsCount = 0;
  45. if (i != 0)
  46. {
  47. var fru = frus[i];
  48. inArgumentsCount = fru.InArguments.Length;
  49. outArgumentsCount = fru.OutArguments.Length;
  50. }
  51. if (cfg.Blocks.Length != 0)
  52. {
  53. RegisterUsage.FixupCalls(cfg.Blocks, frus);
  54. Dominance.FindDominators(cfg);
  55. Dominance.FindDominanceFrontiers(cfg.Blocks);
  56. Ssa.Rename(cfg.Blocks);
  57. Optimizer.RunPass(cfg.Blocks, config);
  58. Rewriter.RunPass(cfg.Blocks, config);
  59. }
  60. funcs[i] = new Function(cfg.Blocks, $"fun{i}", false, inArgumentsCount, outArgumentsCount);
  61. }
  62. var sInfo = StructuredProgram.MakeStructuredProgram(funcs, config);
  63. var info = new ShaderProgramInfo(
  64. config.GetConstantBufferDescriptors(),
  65. config.GetStorageBufferDescriptors(),
  66. config.GetTextureDescriptors(),
  67. config.GetImageDescriptors(),
  68. config.Stage,
  69. config.UsedFeatures.HasFlag(FeatureFlags.InstanceId),
  70. config.UsedFeatures.HasFlag(FeatureFlags.DrawParameters),
  71. config.UsedFeatures.HasFlag(FeatureFlags.RtLayer),
  72. config.ClipDistancesWritten,
  73. config.OmapTargets);
  74. return config.Options.TargetLanguage switch
  75. {
  76. TargetLanguage.Glsl => new ShaderProgram(info, TargetLanguage.Glsl, GlslGenerator.Generate(sInfo, config)),
  77. TargetLanguage.Spirv => new ShaderProgram(info, TargetLanguage.Spirv, SpirvGenerator.Generate(sInfo, config)),
  78. _ => throw new NotImplementedException(config.Options.TargetLanguage.ToString())
  79. };
  80. }
  81. private static TranslatorContext DecodeShader(ulong address, IGpuAccessor gpuAccessor, TranslationOptions options)
  82. {
  83. ShaderConfig config;
  84. DecodedProgram program;
  85. ulong maxEndAddress = 0;
  86. if (options.Flags.HasFlag(TranslationFlags.Compute))
  87. {
  88. config = new ShaderConfig(gpuAccessor, options);
  89. program = Decoder.Decode(config, address);
  90. }
  91. else
  92. {
  93. config = new ShaderConfig(new ShaderHeader(gpuAccessor, address), gpuAccessor, options);
  94. program = Decoder.Decode(config, address + HeaderSize);
  95. }
  96. foreach (DecodedFunction function in program)
  97. {
  98. foreach (Block block in function.Blocks)
  99. {
  100. if (maxEndAddress < block.EndAddress)
  101. {
  102. maxEndAddress = block.EndAddress;
  103. }
  104. }
  105. }
  106. config.SizeAdd((int)maxEndAddress + (options.Flags.HasFlag(TranslationFlags.Compute) ? 0 : HeaderSize));
  107. return new TranslatorContext(address, program, config);
  108. }
  109. internal static FunctionCode[] EmitShader(DecodedProgram program, ShaderConfig config, bool initializeOutputs, out int initializationOperations)
  110. {
  111. initializationOperations = 0;
  112. FunctionMatch.RunPass(program);
  113. foreach (DecodedFunction function in program.OrderBy(x => x.Address).Where(x => !x.IsCompilerGenerated))
  114. {
  115. program.AddFunctionAndSetId(function);
  116. }
  117. FunctionCode[] functions = new FunctionCode[program.FunctionsWithIdCount];
  118. for (int index = 0; index < functions.Length; index++)
  119. {
  120. EmitterContext context = new EmitterContext(program, config, index != 0);
  121. if (initializeOutputs && index == 0)
  122. {
  123. EmitOutputsInitialization(context, config);
  124. initializationOperations = context.OperationsCount;
  125. }
  126. DecodedFunction function = program.GetFunctionById(index);
  127. foreach (Block block in function.Blocks)
  128. {
  129. context.CurrBlock = block;
  130. context.EnterBlock(block.Address);
  131. EmitOps(context, block);
  132. }
  133. functions[index] = new FunctionCode(context.GetOperations());
  134. }
  135. return functions;
  136. }
  137. private static void EmitOutputsInitialization(EmitterContext context, ShaderConfig config)
  138. {
  139. // Compute has no output attributes, and fragment is the last stage, so we
  140. // don't need to initialize outputs on those stages.
  141. if (config.Stage == ShaderStage.Compute || config.Stage == ShaderStage.Fragment)
  142. {
  143. return;
  144. }
  145. if (config.Stage == ShaderStage.Vertex)
  146. {
  147. InitializeOutput(context, AttributeConsts.PositionX, perPatch: false);
  148. }
  149. UInt128 usedAttributes = context.Config.NextInputAttributesComponents;
  150. while (usedAttributes != UInt128.Zero)
  151. {
  152. int index = (int)UInt128.TrailingZeroCount(usedAttributes);
  153. int vecIndex = index / 4;
  154. usedAttributes &= ~(UInt128.One << index);
  155. // We don't need to initialize passthrough attributes.
  156. if ((context.Config.PassthroughAttributes & (1 << vecIndex)) != 0)
  157. {
  158. continue;
  159. }
  160. InitializeOutputComponent(context, AttributeConsts.UserAttributeBase + index * 4, perPatch: false);
  161. }
  162. if (context.Config.NextUsedInputAttributesPerPatch != null)
  163. {
  164. foreach (int vecIndex in context.Config.NextUsedInputAttributesPerPatch.Order())
  165. {
  166. InitializeOutput(context, AttributeConsts.UserAttributePerPatchBase + vecIndex * 16, perPatch: true);
  167. }
  168. }
  169. if (config.NextUsesFixedFuncAttributes)
  170. {
  171. for (int i = 0; i < 4 + AttributeConsts.TexCoordCount; i++)
  172. {
  173. int index = config.GetFreeUserAttribute(isOutput: true, i);
  174. if (index < 0)
  175. {
  176. break;
  177. }
  178. InitializeOutput(context, AttributeConsts.UserAttributeBase + index * 16, perPatch: false);
  179. config.SetOutputUserAttributeFixedFunc(index);
  180. }
  181. }
  182. }
  183. private static void InitializeOutput(EmitterContext context, int baseAttr, bool perPatch)
  184. {
  185. for (int c = 0; c < 4; c++)
  186. {
  187. int attrOffset = baseAttr + c * 4;
  188. InitializeOutputComponent(context, attrOffset, perPatch);
  189. }
  190. }
  191. private static void InitializeOutputComponent(EmitterContext context, int attrOffset, bool perPatch)
  192. {
  193. int c = (attrOffset >> 2) & 3;
  194. context.Copy(perPatch ? AttributePerPatch(attrOffset) : Attribute(attrOffset), ConstF(c == 3 ? 1f : 0f));
  195. }
  196. private static void EmitOps(EmitterContext context, Block block)
  197. {
  198. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  199. {
  200. InstOp op = block.OpCodes[opIndex];
  201. if (context.Config.Options.Flags.HasFlag(TranslationFlags.DebugMode))
  202. {
  203. string instName;
  204. if (op.Emitter != null)
  205. {
  206. instName = op.Name.ToString();
  207. }
  208. else
  209. {
  210. instName = "???";
  211. context.Config.GpuAccessor.Log($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  212. }
  213. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  214. context.Add(new CommentNode(dbgComment));
  215. }
  216. InstConditional opConditional = new InstConditional(op.RawOpCode);
  217. bool noPred = op.Props.HasFlag(InstProps.NoPred);
  218. if (!noPred && opConditional.Pred == RegisterConsts.PredicateTrueIndex && opConditional.PredInv)
  219. {
  220. continue;
  221. }
  222. Operand predSkipLbl = null;
  223. if (Decoder.IsPopBranch(op.Name))
  224. {
  225. // If the instruction is a SYNC or BRK instruction with only one
  226. // possible target address, then the instruction is basically
  227. // just a simple branch, we can generate code similar to branch
  228. // instructions, with the condition check on the branch itself.
  229. noPred = block.SyncTargets.Count <= 1;
  230. }
  231. else if (op.Name == InstName.Bra)
  232. {
  233. noPred = true;
  234. }
  235. if (!(opConditional.Pred == RegisterConsts.PredicateTrueIndex || noPred))
  236. {
  237. Operand label;
  238. if (opIndex == block.OpCodes.Count - 1 && block.HasNext())
  239. {
  240. label = context.GetLabel(block.Successors[0].Address);
  241. }
  242. else
  243. {
  244. label = Label();
  245. predSkipLbl = label;
  246. }
  247. Operand pred = Register(opConditional.Pred, RegisterType.Predicate);
  248. if (opConditional.PredInv)
  249. {
  250. context.BranchIfTrue(label, pred);
  251. }
  252. else
  253. {
  254. context.BranchIfFalse(label, pred);
  255. }
  256. }
  257. context.CurrOp = op;
  258. op.Emitter?.Invoke(context);
  259. if (predSkipLbl != null)
  260. {
  261. context.MarkLabel(predSkipLbl);
  262. }
  263. }
  264. }
  265. }
  266. }