Translator.cs 12 KB

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