OperandManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using Ryujinx.Graphics.Shader.StructuredIr;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
  9. {
  10. class OperandManager
  11. {
  12. private static string[] _stagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
  13. private struct BuiltInAttribute
  14. {
  15. public string Name { get; }
  16. public VariableType Type { get; }
  17. public BuiltInAttribute(string name, VariableType type)
  18. {
  19. Name = name;
  20. Type = type;
  21. }
  22. }
  23. private static Dictionary<int, BuiltInAttribute> _builtInAttributes =
  24. new Dictionary<int, BuiltInAttribute>()
  25. {
  26. { AttributeConsts.Layer, new BuiltInAttribute("gl_Layer", VariableType.S32) },
  27. { AttributeConsts.PointSize, new BuiltInAttribute("gl_PointSize", VariableType.F32) },
  28. { AttributeConsts.PositionX, new BuiltInAttribute("gl_Position.x", VariableType.F32) },
  29. { AttributeConsts.PositionY, new BuiltInAttribute("gl_Position.y", VariableType.F32) },
  30. { AttributeConsts.PositionZ, new BuiltInAttribute("gl_Position.z", VariableType.F32) },
  31. { AttributeConsts.PositionW, new BuiltInAttribute("gl_Position.w", VariableType.F32) },
  32. { AttributeConsts.ClipDistance0, new BuiltInAttribute("gl_ClipDistance[0]", VariableType.F32) },
  33. { AttributeConsts.ClipDistance1, new BuiltInAttribute("gl_ClipDistance[1]", VariableType.F32) },
  34. { AttributeConsts.ClipDistance2, new BuiltInAttribute("gl_ClipDistance[2]", VariableType.F32) },
  35. { AttributeConsts.ClipDistance3, new BuiltInAttribute("gl_ClipDistance[3]", VariableType.F32) },
  36. { AttributeConsts.ClipDistance4, new BuiltInAttribute("gl_ClipDistance[4]", VariableType.F32) },
  37. { AttributeConsts.ClipDistance5, new BuiltInAttribute("gl_ClipDistance[5]", VariableType.F32) },
  38. { AttributeConsts.ClipDistance6, new BuiltInAttribute("gl_ClipDistance[6]", VariableType.F32) },
  39. { AttributeConsts.ClipDistance7, new BuiltInAttribute("gl_ClipDistance[7]", VariableType.F32) },
  40. { AttributeConsts.PointCoordX, new BuiltInAttribute("gl_PointCoord.x", VariableType.F32) },
  41. { AttributeConsts.PointCoordY, new BuiltInAttribute("gl_PointCoord.y", VariableType.F32) },
  42. { AttributeConsts.TessCoordX, new BuiltInAttribute("gl_TessCoord.x", VariableType.F32) },
  43. { AttributeConsts.TessCoordY, new BuiltInAttribute("gl_TessCoord.y", VariableType.F32) },
  44. { AttributeConsts.InstanceId, new BuiltInAttribute("gl_InstanceID", VariableType.S32) },
  45. { AttributeConsts.VertexId, new BuiltInAttribute("gl_VertexID", VariableType.S32) },
  46. { AttributeConsts.FrontFacing, new BuiltInAttribute("gl_FrontFacing", VariableType.Bool) },
  47. // Special.
  48. { AttributeConsts.FragmentOutputDepth, new BuiltInAttribute("gl_FragDepth", VariableType.F32) },
  49. { AttributeConsts.ThreadIdX, new BuiltInAttribute("gl_LocalInvocationID.x", VariableType.U32) },
  50. { AttributeConsts.ThreadIdY, new BuiltInAttribute("gl_LocalInvocationID.y", VariableType.U32) },
  51. { AttributeConsts.ThreadIdZ, new BuiltInAttribute("gl_LocalInvocationID.z", VariableType.U32) },
  52. { AttributeConsts.CtaIdX, new BuiltInAttribute("gl_WorkGroupID.x", VariableType.U32) },
  53. { AttributeConsts.CtaIdY, new BuiltInAttribute("gl_WorkGroupID.y", VariableType.U32) },
  54. { AttributeConsts.CtaIdZ, new BuiltInAttribute("gl_WorkGroupID.z", VariableType.U32) },
  55. { AttributeConsts.LaneId, new BuiltInAttribute("gl_SubGroupInvocationARB", VariableType.U32) },
  56. { AttributeConsts.EqMask, new BuiltInAttribute("unpackUint2x32(gl_SubGroupEqMaskARB).x", VariableType.U32) },
  57. { AttributeConsts.GeMask, new BuiltInAttribute("unpackUint2x32(gl_SubGroupGeMaskARB).x", VariableType.U32) },
  58. { AttributeConsts.GtMask, new BuiltInAttribute("unpackUint2x32(gl_SubGroupGtMaskARB).x", VariableType.U32) },
  59. { AttributeConsts.LeMask, new BuiltInAttribute("unpackUint2x32(gl_SubGroupLeMaskARB).x", VariableType.U32) },
  60. { AttributeConsts.LtMask, new BuiltInAttribute("unpackUint2x32(gl_SubGroupLtMaskARB).x", VariableType.U32) },
  61. // Support uniforms.
  62. { AttributeConsts.FragmentOutputIsBgraBase + 0, new BuiltInAttribute($"{DefaultNames.IsBgraName}[0]", VariableType.Bool) },
  63. { AttributeConsts.FragmentOutputIsBgraBase + 4, new BuiltInAttribute($"{DefaultNames.IsBgraName}[1]", VariableType.Bool) },
  64. { AttributeConsts.FragmentOutputIsBgraBase + 8, new BuiltInAttribute($"{DefaultNames.IsBgraName}[2]", VariableType.Bool) },
  65. { AttributeConsts.FragmentOutputIsBgraBase + 12, new BuiltInAttribute($"{DefaultNames.IsBgraName}[3]", VariableType.Bool) },
  66. { AttributeConsts.FragmentOutputIsBgraBase + 16, new BuiltInAttribute($"{DefaultNames.IsBgraName}[4]", VariableType.Bool) },
  67. { AttributeConsts.FragmentOutputIsBgraBase + 20, new BuiltInAttribute($"{DefaultNames.IsBgraName}[5]", VariableType.Bool) },
  68. { AttributeConsts.FragmentOutputIsBgraBase + 24, new BuiltInAttribute($"{DefaultNames.IsBgraName}[6]", VariableType.Bool) },
  69. { AttributeConsts.FragmentOutputIsBgraBase + 28, new BuiltInAttribute($"{DefaultNames.IsBgraName}[7]", VariableType.Bool) }
  70. };
  71. private Dictionary<AstOperand, string> _locals;
  72. public OperandManager()
  73. {
  74. _locals = new Dictionary<AstOperand, string>();
  75. }
  76. public string DeclareLocal(AstOperand operand)
  77. {
  78. string name = $"{DefaultNames.LocalNamePrefix}_{_locals.Count}";
  79. _locals.Add(operand, name);
  80. return name;
  81. }
  82. public string GetExpression(AstOperand operand, ShaderConfig config, bool cbIndexable)
  83. {
  84. switch (operand.Type)
  85. {
  86. case OperandType.Argument:
  87. return GetArgumentName(operand.Value);
  88. case OperandType.Attribute:
  89. return GetAttributeName(operand, config);
  90. case OperandType.Constant:
  91. return NumberFormatter.FormatInt(operand.Value);
  92. case OperandType.ConstantBuffer:
  93. return GetConstantBufferName(operand.CbufSlot, operand.CbufOffset, config.Stage, cbIndexable);
  94. case OperandType.LocalVariable:
  95. return _locals[operand];
  96. case OperandType.Undefined:
  97. return DefaultNames.UndefinedName;
  98. }
  99. throw new ArgumentException($"Invalid operand type \"{operand.Type}\".");
  100. }
  101. public static string GetConstantBufferName(int slot, int offset, ShaderStage stage, bool cbIndexable)
  102. {
  103. return $"{GetUbName(stage, slot, cbIndexable)}[{offset >> 2}].{GetSwizzleMask(offset & 3)}";
  104. }
  105. private static string GetVec4Indexed(string vectorName, string indexExpr)
  106. {
  107. string result = $"{vectorName}.x";
  108. for (int i = 1; i < 4; i++)
  109. {
  110. result = $"(({indexExpr}) == {i}) ? ({vectorName}.{GetSwizzleMask(i)}) : ({result})";
  111. }
  112. return $"({result})";
  113. }
  114. public static string GetConstantBufferName(int slot, string offsetExpr, ShaderStage stage, bool cbIndexable)
  115. {
  116. return GetVec4Indexed(GetUbName(stage, slot, cbIndexable) + $"[{offsetExpr} >> 2]", offsetExpr + " & 3");
  117. }
  118. public static string GetConstantBufferName(string slotExpr, string offsetExpr, ShaderStage stage)
  119. {
  120. return GetVec4Indexed(GetUbName(stage, slotExpr) + $"[{offsetExpr} >> 2]", offsetExpr + " & 3");
  121. }
  122. public static string GetOutAttributeName(AstOperand attr, ShaderConfig config)
  123. {
  124. return GetAttributeName(attr, config, isOutAttr: true);
  125. }
  126. public static string GetAttributeName(AstOperand attr, ShaderConfig config, bool isOutAttr = false, string indexExpr = "0")
  127. {
  128. int value = attr.Value;
  129. char swzMask = GetSwizzleMask((value >> 2) & 3);
  130. if (value >= AttributeConsts.UserAttributeBase && value < AttributeConsts.UserAttributeEnd)
  131. {
  132. value -= AttributeConsts.UserAttributeBase;
  133. string prefix = isOutAttr
  134. ? DefaultNames.OAttributePrefix
  135. : DefaultNames.IAttributePrefix;
  136. if ((config.Flags & TranslationFlags.Feedback) != 0)
  137. {
  138. string name = $"{prefix}{(value >> 4)}_{swzMask}";
  139. if (config.Stage == ShaderStage.Geometry && !isOutAttr)
  140. {
  141. name += $"[{indexExpr}]";
  142. }
  143. return name;
  144. }
  145. else
  146. {
  147. string name = $"{prefix}{(value >> 4)}";
  148. if (config.Stage == ShaderStage.Geometry && !isOutAttr)
  149. {
  150. name += $"[{indexExpr}]";
  151. }
  152. return name + '.' + swzMask;
  153. }
  154. }
  155. else
  156. {
  157. if (value >= AttributeConsts.FragmentOutputColorBase && value < AttributeConsts.FragmentOutputColorEnd)
  158. {
  159. value -= AttributeConsts.FragmentOutputColorBase;
  160. return $"{DefaultNames.OAttributePrefix}{(value >> 4)}.{swzMask}";
  161. }
  162. else if (_builtInAttributes.TryGetValue(value & ~3, out BuiltInAttribute builtInAttr))
  163. {
  164. // TODO: There must be a better way to handle this...
  165. if (config.Stage == ShaderStage.Fragment)
  166. {
  167. switch (value & ~3)
  168. {
  169. case AttributeConsts.PositionX: return "(gl_FragCoord.x / fp_renderScale[0])";
  170. case AttributeConsts.PositionY: return "(gl_FragCoord.y / fp_renderScale[0])";
  171. case AttributeConsts.PositionZ: return "gl_FragCoord.z";
  172. case AttributeConsts.PositionW: return "gl_FragCoord.w";
  173. }
  174. }
  175. string name = builtInAttr.Name;
  176. if (config.Stage == ShaderStage.Geometry && (value & AttributeConsts.SpecialMask) == 0 && !isOutAttr)
  177. {
  178. name = $"gl_in[{indexExpr}].{name}";
  179. }
  180. return name;
  181. }
  182. }
  183. // TODO: Warn about unknown built-in attribute.
  184. return isOutAttr ? "// bad_attr0x" + value.ToString("X") : "0.0";
  185. }
  186. public static string GetUbName(ShaderStage stage, int slot, bool cbIndexable)
  187. {
  188. if (cbIndexable)
  189. {
  190. return GetUbName(stage, NumberFormatter.FormatInt(slot, VariableType.S32));
  191. }
  192. return $"{GetShaderStagePrefix(stage)}_{DefaultNames.UniformNamePrefix}{slot}_{DefaultNames.UniformNameSuffix}";
  193. }
  194. private static string GetUbName(ShaderStage stage, string slotExpr)
  195. {
  196. return $"{GetShaderStagePrefix(stage)}_{DefaultNames.UniformNamePrefix}[{slotExpr}].{DefaultNames.DataName}";
  197. }
  198. public static string GetSamplerName(ShaderStage stage, AstTextureOperation texOp, string indexExpr)
  199. {
  200. string suffix = texOp.CbufSlot < 0 ? $"_tcb_{texOp.Handle:X}" : $"_cb{texOp.CbufSlot}_{texOp.Handle:X}";
  201. if ((texOp.Type & SamplerType.Indexed) != 0)
  202. {
  203. suffix += $"a[{indexExpr}]";
  204. }
  205. return GetShaderStagePrefix(stage) + "_" + DefaultNames.SamplerNamePrefix + suffix;
  206. }
  207. public static string GetImageName(ShaderStage stage, AstTextureOperation texOp, string indexExpr)
  208. {
  209. string suffix = texOp.CbufSlot < 0 ? $"_tcb_{texOp.Handle:X}_{texOp.Format.ToGlslFormat()}" : $"_cb{texOp.CbufSlot}_{texOp.Handle:X}_{texOp.Format.ToGlslFormat()}";
  210. if ((texOp.Type & SamplerType.Indexed) != 0)
  211. {
  212. suffix += $"a[{indexExpr}]";
  213. }
  214. return GetShaderStagePrefix(stage) + "_" + DefaultNames.ImageNamePrefix + suffix;
  215. }
  216. public static string GetShaderStagePrefix(ShaderStage stage)
  217. {
  218. int index = (int)stage;
  219. if ((uint)index >= _stagePrefixes.Length)
  220. {
  221. return "invalid";
  222. }
  223. return _stagePrefixes[index];
  224. }
  225. private static char GetSwizzleMask(int value)
  226. {
  227. return "xyzw"[value];
  228. }
  229. public static string GetArgumentName(int argIndex)
  230. {
  231. return $"{DefaultNames.ArgumentNamePrefix}{argIndex}";
  232. }
  233. public static VariableType GetNodeDestType(CodeGenContext context, IAstNode node)
  234. {
  235. if (node is AstOperation operation)
  236. {
  237. // Load attribute basically just returns the attribute value.
  238. // Some built-in attributes may have different types, so we need
  239. // to return the type based on the attribute that is being read.
  240. if (operation.Inst == Instruction.LoadAttribute)
  241. {
  242. return GetOperandVarType((AstOperand)operation.GetSource(0));
  243. }
  244. else if (operation.Inst == Instruction.Call)
  245. {
  246. AstOperand funcId = (AstOperand)operation.GetSource(0);
  247. Debug.Assert(funcId.Type == OperandType.Constant);
  248. return context.GetFunction(funcId.Value).ReturnType;
  249. }
  250. else if (operation is AstTextureOperation texOp &&
  251. (texOp.Inst == Instruction.ImageLoad ||
  252. texOp.Inst == Instruction.ImageStore))
  253. {
  254. return texOp.Format.GetComponentType();
  255. }
  256. return GetDestVarType(operation.Inst);
  257. }
  258. else if (node is AstOperand operand)
  259. {
  260. if (operand.Type == OperandType.Argument)
  261. {
  262. int argIndex = operand.Value;
  263. return context.CurrentFunction.GetArgumentType(argIndex);
  264. }
  265. return GetOperandVarType(operand);
  266. }
  267. else
  268. {
  269. throw new ArgumentException($"Invalid node type \"{node?.GetType().Name ?? "null"}\".");
  270. }
  271. }
  272. private static VariableType GetOperandVarType(AstOperand operand)
  273. {
  274. if (operand.Type == OperandType.Attribute)
  275. {
  276. if (_builtInAttributes.TryGetValue(operand.Value & ~3, out BuiltInAttribute builtInAttr))
  277. {
  278. return builtInAttr.Type;
  279. }
  280. }
  281. return OperandInfo.GetVarType(operand);
  282. }
  283. }
  284. }