Translator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. config.OmapTargets);
  86. return program;
  87. }
  88. private static TranslatorContext DecodeShader(ulong address, IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts)
  89. {
  90. ShaderConfig config;
  91. DecodedProgram program;
  92. ulong maxEndAddress = 0;
  93. if ((options.Flags & TranslationFlags.Compute) != 0)
  94. {
  95. config = new ShaderConfig(gpuAccessor, options, counts);
  96. program = Decoder.Decode(config, address);
  97. }
  98. else
  99. {
  100. config = new ShaderConfig(new ShaderHeader(gpuAccessor, address), gpuAccessor, options, counts);
  101. program = Decoder.Decode(config, address + HeaderSize);
  102. }
  103. foreach (DecodedFunction function in program)
  104. {
  105. foreach (Block block in function.Blocks)
  106. {
  107. if (maxEndAddress < block.EndAddress)
  108. {
  109. maxEndAddress = block.EndAddress;
  110. }
  111. if (!config.UsedFeatures.HasFlag(FeatureFlags.Bindless))
  112. {
  113. for (int index = 0; index < block.OpCodes.Count; index++)
  114. {
  115. InstOp op = block.OpCodes[index];
  116. if (op.Props.HasFlag(InstProps.Tex))
  117. {
  118. int tidB = (int)((op.RawOpCode >> 36) & 0x1fff);
  119. config.TextureHandlesForCache.Add(tidB);
  120. }
  121. }
  122. }
  123. }
  124. }
  125. config.SizeAdd((int)maxEndAddress + (options.Flags.HasFlag(TranslationFlags.Compute) ? 0 : HeaderSize));
  126. return new TranslatorContext(address, program, config);
  127. }
  128. internal static FunctionCode[] EmitShader(DecodedProgram program, ShaderConfig config, bool initializeOutputs, out int initializationOperations)
  129. {
  130. initializationOperations = 0;
  131. FunctionMatch.RunPass(program);
  132. foreach (DecodedFunction function in program.OrderBy(x => x.Address).Where(x => !x.IsCompilerGenerated))
  133. {
  134. program.AddFunctionAndSetId(function);
  135. }
  136. FunctionCode[] functions = new FunctionCode[program.FunctionsWithIdCount];
  137. for (int index = 0; index < functions.Length; index++)
  138. {
  139. EmitterContext context = new EmitterContext(program, config, index != 0);
  140. if (initializeOutputs && index == 0)
  141. {
  142. EmitOutputsInitialization(context, config);
  143. initializationOperations = context.OperationsCount;
  144. }
  145. DecodedFunction function = program.GetFunctionById(index);
  146. foreach (Block block in function.Blocks)
  147. {
  148. context.CurrBlock = block;
  149. context.MarkLabel(context.GetLabel(block.Address));
  150. EmitOps(context, block);
  151. }
  152. functions[index] = new FunctionCode(context.GetOperations());
  153. }
  154. return functions;
  155. }
  156. private static void EmitOutputsInitialization(EmitterContext context, ShaderConfig config)
  157. {
  158. // Compute has no output attributes, and fragment is the last stage, so we
  159. // don't need to initialize outputs on those stages.
  160. if (config.Stage == ShaderStage.Compute || config.Stage == ShaderStage.Fragment)
  161. {
  162. return;
  163. }
  164. if (config.Stage == ShaderStage.Vertex)
  165. {
  166. InitializeOutput(context, AttributeConsts.PositionX, perPatch: false);
  167. }
  168. int usedAttributes = context.Config.UsedOutputAttributes;
  169. while (usedAttributes != 0)
  170. {
  171. int index = BitOperations.TrailingZeroCount(usedAttributes);
  172. InitializeOutput(context, AttributeConsts.UserAttributeBase + index * 16, perPatch: false);
  173. usedAttributes &= ~(1 << index);
  174. }
  175. int usedAttributesPerPatch = context.Config.UsedOutputAttributesPerPatch;
  176. while (usedAttributesPerPatch != 0)
  177. {
  178. int index = BitOperations.TrailingZeroCount(usedAttributesPerPatch);
  179. InitializeOutput(context, AttributeConsts.UserAttributeBase + index * 16, perPatch: true);
  180. usedAttributesPerPatch &= ~(1 << index);
  181. }
  182. if (config.NextUsesFixedFuncAttributes)
  183. {
  184. for (int i = 0; i < 4 + AttributeConsts.TexCoordCount; i++)
  185. {
  186. int index = config.GetFreeUserAttribute(isOutput: true, i);
  187. if (index < 0)
  188. {
  189. break;
  190. }
  191. InitializeOutput(context, AttributeConsts.UserAttributeBase + index * 16, perPatch: false);
  192. config.SetOutputUserAttributeFixedFunc(index);
  193. }
  194. }
  195. }
  196. private static void InitializeOutput(EmitterContext context, int baseAttr, bool perPatch)
  197. {
  198. for (int c = 0; c < 4; c++)
  199. {
  200. int attrOffset = baseAttr + c * 4;
  201. context.Copy(perPatch ? AttributePerPatch(attrOffset) : Attribute(attrOffset), ConstF(c == 3 ? 1f : 0f));
  202. }
  203. }
  204. private static void EmitOps(EmitterContext context, Block block)
  205. {
  206. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  207. {
  208. InstOp op = block.OpCodes[opIndex];
  209. if (context.Config.Options.Flags.HasFlag(TranslationFlags.DebugMode))
  210. {
  211. string instName;
  212. if (op.Emitter != null)
  213. {
  214. instName = op.Name.ToString();
  215. }
  216. else
  217. {
  218. instName = "???";
  219. context.Config.GpuAccessor.Log($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  220. }
  221. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  222. context.Add(new CommentNode(dbgComment));
  223. }
  224. InstConditional opConditional = new InstConditional(op.RawOpCode);
  225. bool noPred = op.Props.HasFlag(InstProps.NoPred);
  226. if (!noPred && opConditional.Pred == RegisterConsts.PredicateTrueIndex && opConditional.PredInv)
  227. {
  228. continue;
  229. }
  230. Operand predSkipLbl = null;
  231. if (Decoder.IsPopBranch(op.Name))
  232. {
  233. // If the instruction is a SYNC or BRK instruction with only one
  234. // possible target address, then the instruction is basically
  235. // just a simple branch, we can generate code similar to branch
  236. // instructions, with the condition check on the branch itself.
  237. noPred = block.SyncTargets.Count <= 1;
  238. }
  239. else if (op.Name == InstName.Bra)
  240. {
  241. noPred = true;
  242. }
  243. if (!(opConditional.Pred == RegisterConsts.PredicateTrueIndex || noPred))
  244. {
  245. Operand label;
  246. if (opIndex == block.OpCodes.Count - 1 && block.HasNext())
  247. {
  248. label = context.GetLabel(block.Successors[0].Address);
  249. }
  250. else
  251. {
  252. label = Label();
  253. predSkipLbl = label;
  254. }
  255. Operand pred = Register(opConditional.Pred, RegisterType.Predicate);
  256. if (opConditional.PredInv)
  257. {
  258. context.BranchIfTrue(label, pred);
  259. }
  260. else
  261. {
  262. context.BranchIfFalse(label, pred);
  263. }
  264. }
  265. context.CurrOp = op;
  266. op.Emitter?.Invoke(context);
  267. if (predSkipLbl != null)
  268. {
  269. context.MarkLabel(predSkipLbl);
  270. }
  271. }
  272. }
  273. }
  274. }